eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

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

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Course – LJU – NPI (tag = JUnit)
announcement - icon

Master the most popular testing framework for Java, through the Learn JUnit course:

>> LEARN JUNIT

1. Overview

JUnit is one of the most popular unit testing frameworks available in Java. Moreover, Spring Boot provides it as a default test dependency for its applications.

In this tutorial, we’ll compare two JUnit runners – SpringRunner and MockitoJUnitRunner. We’ll understand their purpose and the key differences between them.

2. @RunWith vs @ExtendWith

Before we go further, let’s recap how we can extend basic JUnit functionality or integrate it with other libraries.

JUnit 4 allows us to implement custom Runner classes responsible for running tests by applying extra functionalities. To invoke a custom runner, we annotate a test class using a @RunWith annotation:

@RunWith(CustomRunner.class)
class JUnit4Test {
    // ...
}

As we know, JUnit 4 is now in a legacy state, succeeded by JUnit 5. The newer version brings us a completely new engine with a rewritten API. It also changes the concept of the extension model. Instead of implementing custom Runner or Rule classes, we can now use the Extension API with an @ExtendWith annotation:

@ExtendWith(CustomExtensionOne.class)
@ExtendWith(CustomExtensionTwo.class)
class JUnit5Test {
    // ...
}

Unlike the previous runner model, we can provide multiple extensions to a single class. Most of the previously delivered runners were also rewritten for their extension counterparts.

3. Spring Example Application

For better understanding, let’s introduce a simple Spring Boot application – a converter that maps the given strings to uppercase.

Let’s start with the implementation of the data provider:

@Component
public class DataProvider {
    
    private final List<String> memory = List.of("baeldung", "java", "dummy");
    
    public Stream<String> getValues() {
        return memory.stream();
    }
}

We’ve just created a Spring Component with hardcoded string values. Moreover, it provides a single method to stream these strings.

Secondly, let’s implement a service class that transforms our values:

@Service
public class StringConverter {
    
    private final DataProvider dataProvider;

    @Autowired
    public StringConverter(DataProvider dataProvider) {
        this.dataProvider = dataProvider;
    }
    
    public List<String> convert() {
        return dataProvider.getValues().map(String::toUpperCase).toList();
    }
}

It’s a simple bean that fetches data from the previously created DataProvider and applies uppercase mapping.

Now, we can use our application to create JUnit tests. We’ll see the difference between SpringRunner and MockitoJUnitRunner classes.

4. MockitoJUnitRunner

As we know, Mockito is a mocking framework that’s used in conjunction with other testing frameworks to return dummy data and avoid external dependencies. This library provides us MockitoJUnitRunner – a dedicated JUnit 4 runner to integrate Mockito and take advantage of the library’s capabilities.

Let’s now create the first test for StringConverter:

public class StringConverterTest {
    @Mock
    private DataProvider dataProvider;

    @InjectMocks
    private StringConverter stringConverter;
    
    @Test
    public void givenStrings_whenConvert_thenReturnUpperCase() {
        Mockito.when(dataProvider.getValues()).thenReturn(Stream.of("first", "second"));

        val result = stringConverter.convert();

        Assertions.assertThat(result).contains("FIRST", "SECOND");
    }
}

We’ve just mocked our DataProvider to return two strings. But if we run it, the test fails:

java.lang.NullPointerException: Cannot invoke "DataProvider.getValues()" because "this.dataProvider" is null

That is because our mock isn’t properly initialized. The @Mock and @InjectMocks annotations currently do nothing. We can fix this by implementing the init() method:

@Before
public void init() {
    MockitoAnnotations.openMocks(this);
}

If we don’t want to use annotations, we can also create and inject mocks programmatically:

@Before
public void init() {
    dataProvider = Mockito.mock(DataProvider.class);
    stringConverter = new StringConverter(dataProvider);
}

We’ve just initialized mocks programmatically using the Mockito API. Now, the test works as expected and our assertions succeed.

Next, let’s go back to our first version, remove the init() method, and annotate the class using the MockitoJUnitRunner:

@RunWith(MockitoJUnitRunner.class)
public class StringConverterTest {
    // ...
}

Again, the test succeeds. We invoked a custom runner, which took responsibility for managing our mocks. We didn’t have to initialize them manually.

To summarize, MockitoJUnitRunner is a dedicated runner for the Mockito framework. It’s responsible for initializing @Mock, @Spy, and @InjectMock annotations, so that explicit usage of MockitoAnnotations.openMocks() is not necessary. Moreover, it detects unused stubs in the test and validates mock usage after each test method, just like Mockito.validateMockitoUsage() does.

We should remember that all runners are originally designed for JUnit 4. If we want to support Mockito annotations with JUnit 5, we can use MockitoExtension:

@ExtendWith(MockitoExtension.class)
public class StringConverterTest {
    // ...
}

This extension ports the functionalities from the MockitoJUnitRunner into the new extension model.

5. SpringRunner

If we analyze our test more deeply, we’ll see that, despite using Spring, we don’t start a Spring Container at all. Let’s now try to modify our example and initialize a Spring Context.

First, instead of MockitoJUnitRunner, let’s just replace it with the SpringRunner class and check the results:

@RunWith(SpringRunner.class)
public class StringConverterTest {
    // ...
}

As before, the test succeeds and the mocks are properly initialized. Moreover, a Spring Context is also started. We can conclude that SpringRunner not only enables Mockito annotations, just like MockitoJUnitRunner does, but also initializes a Spring Context.

Of course, we haven’t seen Spring’s full potential yet in our test. Instead of constructing new objects, we can inject them as Spring beans. As we know, the Spring test module has the Mockito integration by default, which also provides us the @MockBean and @SpyBean annotations – integrating mocks and beans features together.

Let’s rewrite our test:

@ContextConfiguration(classes = StringConverter.class)
@RunWith(SpringRunner.class)
public class StringConverterTest {
    @MockBean
    private DataProvider dataProvider;

    @Autowired
    private StringConverter stringConverter;

    // ...
}

We just replaced the @Mock annotation with @MockBean next to the DataProvider object. It’s still a mock, but can now also be used as a bean. We also configured our Spring Context via the @ContextConfiguration class annotation and injected StringConverter. As a result, the test still succeeds, but it now uses Spring beans and Mockito together.

To sum up, SpringRunner is a custom runner created for JUnit 4 that provides the functionality of the Spring TestContext Framework. Since Mockito is the default mocking framework integrated with the Spring stack, the runner brings full support provided by MockitoJUnitRunner. Sometimes, we may also come across SpringJUnit4ClassRunner, which is an alias, and we can use both alternately.

If we’re looking for an extension counterpart for the SpringRunner, we should use SpringExtension:

@ExtendWith(SpringExtension.class)
public class StringConverterTest {
    // ...
}

As JUnit 5 is the default testing framework in the Spring Boot stack, the extension has been integrated with many test slice annotations, including @SpringBootTest.

6. Conclusion

In this article, we learned the difference between SpringRunner and MockitoJUnitRunner.

We started with a recap of the extension model used in JUnit 4 and JUnit 5. JUnit 4 uses dedicated runners while JUnit 5 supports extensions. At the same time, we can provide a single runner or multiple extensions.

Then, we looked at MockitoJUnitRunner, which enables the Mockito framework to be supported in our JUnit 4 tests. In general, we can configure our mocks via dedicated @Mock, @Spy, and @InjectMocks annotations without any initialization methods.

Finally, we discussed SpringRunner, which releases all the advantages of cooperation between the Mockito and Spring frameworks. It not only supports the basic Mockito annotations but also enables Spring ones: @MockBean and @SpyBean. The mocks constructed in this way can be injected using the Spring Context.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

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

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook – Mockito – NPI (tag=Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

>> Download the eBook

eBook Jackson – NPI EA – 3 (cat = Jackson)