Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating strict mock when using @MockBean of spring boot?

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.

like image 527
Viktor Avatar asked Feb 01 '17 09:02

Viktor


People also ask

What is @MockBean vs @mock?

@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.

What is @MockBean in Spring Boot?

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 .

How do you inject a mock in SpringBootTest?

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 .


1 Answers

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.

like image 145
František Hartman Avatar answered Oct 24 '22 03:10

František Hartman