jeudi 22 novembre 2018

MockBean stubbing ineffective

I have a configuration class with a few MockBeans replacing actual beans in context for tests.

@Configuration
public class MyTestConfig {
    @MockBean
    private MyService myService;
}

I use those mocks in my tests:

@Import({ MyTestConfig .class })
public class MyTest {
    @Autowired
    private MyService myService;

    @Test
    public void aTest() {
        ...
    }
}

First the idea was to add the stubbing in this MyTestConfig configuration class, so that the mock is pre-made for all tests, so I did it in a @PostConstruct method, and it worked just fine - the mock in test did return the expected value:

@PostConstruct
public void init() {
    when(myService.foo("say hello")).thenReturn("Hello world");
}

It turned out though, that constructing a pre-made mock suitable for all test can be tricky, so we decided to move the stubbing to tests.

@Test
public void aTest() {
    when(myService.foo("say hello")).thenReturn("Hello world");
}

And this doesn't work - the stubbed method returns null. We want to leave MockBeans in the configuration class, but stub them in tests, so any advice on why the stubbing is ineffective?

Spring Boot 2.0.5, Mockito 2.22.0

Aucun commentaire:

Enregistrer un commentaire