Spring Unit Testing with Mockito

Let's rewrite the unit test by mocking the dependency using Mockito.

The RecommenderImplementation class has a dependency on the Filter interface. Ideally, when writing unit tests, we should only focus on the class under test and mock the dependencies instead of initializing the dependency. We will now write a test for the same class using Mockito.

mockito-core dependency

To test using the Mockito framework, we need the mockito-core dependency, which can be added to pom.xml as follows:


Note that this dependency is automatically available if springboot-starter-test is included in the pom.xml file.

We are testing the RecommenderImplementation class that depends on the Filter interface and gets data from it by calling the getRecommendations() method of the interface. This is not good practice because we are not testing the interface right now. We should not be calling the interface method when testing our class.

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.