Combining Spring Integration Testing with Mockito

Integration tests…they are perfect for testing your data flows. You send some request to your application and can control how data is being processed throughout your application. You see how request is received by your controller, then it’s sent to service, dao or other layers, that you have in your application. Sometimes you don’t want some layer to do real work in Spring. For instance, your dao layer is using some native queries to get data from database, and some embedded database doesn’t support some query syntax. Naturally, you still want to have your integration tests, but without a real call to database. What can we do in this situation ? I’d suggest to mock this dao layer, using mockito. Let’s demonstrate how it works ?

######Project setup
I use Spring Initialzr to setup projects, so let’s create a simple Spring Boot application. Code can be found here.

If I were you, I’d have two questions: why exampleDao is missing annotation @Mock and what is @ActiveProfiles("test")Because we are createa mock using Spring dependency injection, we don’t need to annotate our mock field with any @Mock annotations.

TestConfiguration - test configuration, which has one method of ExampleDao returning type. Notice, how it’s returned.

TestConfiguration also has @Profile("test") annotation, which is an indicator, that this configuration should run only on test profile. @Profile, together with @ActiveProfiles are loading TestConfiguration inside our test. That’s why ExampleDao is annotated as a spring bean, because we need to get it from context.