Spring Boot 2 With JUnit 5 and Mockito 2 for Unit, Integration Testing

DZone 's Guide to

Spring Boot 2 With JUnit 5 and Mockito 2 for Unit, Integration Testing

Want to learn more about using Spring Boot 2 for integration and unit testing? Check out this post to learn more about testing with JUnit 5 and Mockito 2.

· Java Zone ·
Free Resource

In this post, we will explain how to use JUnit 5 and Mockito 2 with Spring Boot 2 for unit and integration testing. Let's get started!

Image title

First, if you are interested in reading more about Junit 5 and Mockito 2, please check out the following links: JUnit 5 and Mockito 2.

Here, we will demonstrate the following :

  1. Gradle configuration for JUnit 5 with Spring Boot 2
  2. How to define and execute the unit test with JUnit 5 and Mockito 2
  3. How to define and execute Spring Boot integration testing with Junit 5

Gradle Configuration for JUnit 5 With Spring Boot 2

To add the needed JUnit 5 dependencies, here is what you will need to implement, with the entire code sample available on GitHub:

dependencies {
    compile group: 'org.springframework.boot', name: 'spring-boot-starter'
    testCompile "org.mockito:mockito-core:2.+"

How to Define and Execute the Unit Test With JUnit 5 and Mockito 2

To run the JUnit 5 test case with Mockito2, we use Jupiter extensions support, and here, we will use the Mockito extension. The purpose of the JUnit 5 extensions is to extend the behavior of test classes or methods, and these can be reused for multiple tests.

@DisplayName("Spring boot 2 mockito2 Junit5 example")
public class ShowServiceTests {
    private static final String MOCK_OUTPUT = "Mocked show label";

    private TextService textService;

    private ShowService showService;

    void setMockOutput() {

    @DisplayName("Mock the output of the text service using mockito")
    public void contextLoads() {
        assertEquals(showService.getShowLable(), MOCK_OUTPUT);

How to Define and Execute Spring Boot Integration Test With JUnit 5

Now, if we want to call the real service and not the mocked one for the integration test with JUnit 5, we will use the Spring extension to support that. Now, your integration test is running with JUnit 5 support as well.

public class SpringBootJunit5IntegrationTest {

    private ShowService showService;

    @DisplayName("Integration test which will get the actual output of text service")
    public void contextLoads() {
        assertEquals(showService.getShowLable(), ORIGINAL_OUTPUT);

Well, that's it! I hope this helped you get started using JUnit 5 in your Spring Boot application.

You can find the entire sample code in GitHub

java, junit 5, mockito, spring boot 2, tutorial, unit testing

Published at DZone with permission of Mahmoud Romeh , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}