I use @MockBean
of spring boot (with @RunWith(SpringRunner.class)
) and everything was ok so far.
However the mock provides default implementation for every method of the mocked class so I cannot check if only those methods were called that I expected to be called, i.e. I would like to create strict mock.
Is that possible with @MockBean
?
I don't insist on creating strict mocks if somebody has a good idea how to check if only those methods were called that I expected.
Thanks for the help in advance!
Regards,
V.
@Mock is used when the application context is not up and you need to Mock a service/Bean. @MockBean is used when the application context(in terms of testing) is up and you need to mock a service/Bean.
Annotation Type MockBean. Annotation that can be used to add mocks to a Spring ApplicationContext . Can be used as a class level annotation or on fields in either @Configuration classes, or test classes that are @RunWith the SpringRunner . Mocks can be registered by type or by bean name .
If you want to create just a Mockito test you could use the annotation @RunWith(MockitoJUnitRunner. class) instead of @SpringBootTest . But if you want to create a Spring Boot integration test then you should use @MockBean instead of @Mock and @Autowired instead of @InjectMocks .
With Mockito you can verify that a method was called:
verify(mockOne).add("one");
or that it was never called (never() is more readable alias for times(0)):
verify(mockOne, never()).remove("two");
Or you can verify that no other method was called:
verify(mockOne).add("one"); // check this one
verifyNoMoreInteractions(mockOne); // and nothing else
For more information see the Mockito documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With