1. Overview

In this tutorial, we’ll discuss how to use dependency injection to insert Mockito mocks into Spring Beans for unit testing.

In real-world applications, where components often depend on accessing external systems, it’s important to provide proper test isolation, so that we can focus on testing the functionality of a given unit without having to involve the whole class hierarchy for each test.

Injecting a mock is a clean way to introduce such isolation.

2. Maven Dependencies

We need the following Maven dependencies for the unit tests and mock objects:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>2.21.0</version>
</dependency>

We decided to use Spring Boot for this example, but classic Spring will also work fine.

3. Writing the Test

3.1. The Business Logic

First, let’s create a simple service that we’ll be testing:

@Service
public class NameService {
    public String getUserName(String id) {
        return "Real user name";
    }
}

Then we’ll inject it into the UserService class:

@Service
public class UserService {

    private NameService nameService;

    @Autowired
    public UserService(NameService nameService) {
        this.nameService = nameService;
    }

    public String getUserName(String id) {
        return nameService.getUserName(id);
    }
}

For this article, the given classes return a single name regardless of the id provided. This is done so that we don’t get distracted by testing any complex logic.

We’ll also need a standard Spring Boot main class to scan the beans and initialize the application:

@SpringBootApplication
public class MocksApplication {
    public static void main(String[] args) {
        SpringApplication.run(MocksApplication.class, args);
    }
}

3.2. The Tests

Now let’s move on to the test logic. First of all, we have to configure the application context for the tests:

@Profile("test")
@Configuration
public class NameServiceTestConfiguration {
    @Bean
    @Primary
    public NameService nameService() {
        return Mockito.mock(NameService.class);
    }
}

The @Profile annotation tells Spring to apply this configuration only when the “test” profile is active. The @Primary annotation is there to make sure this instance is used instead of a real one for autowiring. The method itself creates and returns a Mockito mock of our NameService class.

Now we can write the unit test:

@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MocksApplication.class)
public class UserServiceUnitTest {

    @Autowired
    private UserService userService;

    @Autowired
    private NameService nameService;

    @Test
    public void whenUserIdIsProvided_thenRetrievedNameIsCorrect() {
        Mockito.when(nameService.getUserName("SomeId")).thenReturn("Mock user name");
        String testName = userService.getUserName("SomeId");
        Assert.assertEquals("Mock user name", testName);
    }
}

We use the @ActiveProfiles annotation to enable the “test” profile and activate the mock configuration we wrote earlier. As a result, Spring autowires a real instance of the UserService class, but a mock of the NameService class. The test itself is a fairly typical JUnit+Mockito test. We configure the desired behavior of the mock, then call the method that we want to test, and assert that it returns the value we expect.

It’s also possible (though not recommended) to avoid using environment profiles in such tests. To do so, we remove the @Profile and @ActiveProfiles annotations, and add an @ContextConfiguration(classes = NameServiceTestConfiguration.class) annotation to the UserServiceTest class.

4. Conclusion

In this brief article, we learned how easy it is to inject Mockito mocks into Spring Beans.

As usual, all the code samples are available over on GitHub.