1

Versions:

Java: 1.8
Spring Boot: 1.5.4.RELEASE

Application Main:

@SpringBootApplication
public class SpringbootMockitoApplication implements CommandLineRunner {
    @Autowired
    MyCoolService myCoolService;

    public static void main(String[] args) {
        SpringApplication.run(SpringbootMockitoApplication.class, args);
    }

    @Override
    public void run(String... strings) throws Exception {
        System.out.println(myCoolService.talkToMe());
    }
}

My Service Interface:

public interface MyCoolService {
  public String talkToMe();
}

My Service Implementation:

@Service
public class MyCoolServiceImpl implements MyCoolService {

  @Override
  public String talkToMe() {
    return "Epic Win";
  }
}

My Test class:

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootMockitoApplicationTests {

    @MockBean
    private MyCoolService myCoolService;

    @Test
    public void test() {
        when(myCoolService.talkToMe()).thenReturn("I am greater than epic");

    }

}

Expected Output: I am greater than epic Actual Output: null

I simply want to replace the bean instance in the context with a mock that will return "I am greater than epic". Have I misconfigured something here?

4

1 回答 1

4

The run method of any CommandLineRunners is called as part of SpringApplication being run. This happens when the test framework is bootstrapping the application context for your tests. Crucially, this is before your test method has set any expectations on your MyCoolService mock. As a result the mock returns null when talkToMe() is called.

Something may have been lost in reducing your problem to a simple example, but I don't think I'd use an integration test here. Instead, I'd unit test your CommandLineRunner with a mock service. To so so, I'd recommend moving to constructor injection so that you can pass the mock directly into the service's constructor.

于 2017-06-15T20:32:50.543 回答