Authors Top

If you have a few years of experience in the Java ecosystem, and you’d like to share that with the community, have a look at our Contribution Guidelines.

Spring Top – Temp

Get started with Spring 5 and Spring Boot 2, through the reference Learn Spring course:

Lightrun – Third Party Code
announcement - icon

Flakiness in REST requests is a common issue. A request can get a 200 OK in one scenario and a 409 next time. Sometimes a request can even succeed and fail intermittently on the same exact request. In short, working over HTTP can be a bit of a mess without solid tooling.

Also, while it’s easy enough to debug these issues locally when developing the application, we’re talking about production here - we can’t afford the downtime while you’re stepping in and out of code. Uptime is kind of the whole point.

With Lightrun, you can get the same level of access you get with a local debugger or profiler - no downtime required. You can add logs, metrics, and snapshots (think breakpoints, but without stopping the running service), in a safe and read-only manner - without redeploying, restarting, or even stopping the running service. Performance and security are maintained throughout the process.

Learn how to debug a live REST API (built with Spring, of course), using Lightrun, in this 5-minute tutorial:

>> Debugging REST Requests in Spring-Based applications using the Lightrun Platform

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:


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:

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

Then we'll inject it into the UserService class:

public class UserService {

    private NameService nameService;

    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:

public class MocksApplication {
    public static void main(String[] args) {, 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:

public class NameServiceTestConfiguration {
    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:

@SpringApplicationConfiguration(classes = MocksApplication.class)
public class UserServiceUnitTest {

    private UserService userService;

    private NameService nameService;

    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.

Spring bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

Junit footer banner
Comments are closed on this article!