Skip to content

Grokem · https://www.grokem.com/programming/how-to-test-java-code-with-junit-5-and-mockito-a-beginners-gradle-project

ProgrammingTutorialBeginner level

How to test Java code with JUnit 5 and Mockito: a beginner's Gradle project

Build a small Gradle project, write JUnit 5 tests, and replace a dependency with a Mockito mock. You finish with a green test run you can check in the terminal.

Krishna Sharma

Technical Writer

Published Updated
  • 30 min to complete
  • 0 sec

Tested with
  • Gradle4.6
  • JUnit Jupiter (JUnit 5)5.7.1
  • Mockito (mockito-core)5.24.0
  • Java
Your progress
  1. How to test Java code with JUnit 5 and Mockito: a beginner's Gradle project6 min(finished)
    0%

Before you start

4
  • A JDK installed and on your PATH (check the Mockito documentation for the minimum Java version of your Mockito release)
  • Gradle installed, 4.6 or newer
  • A terminal and a text editor or IDE
  • Basic Java: classes, interfaces and methods

You will build a tiny order calculator and test it three ways. The project uses Gradle to compile and run the tests, JUnit 5 to define and check them, and Mockito to stand in for a collaborator you do not want to run for real.

The result is a gradle test run that prints three passed tests and ends with BUILD SUCCESSFUL.

Versions used: Gradle 4.6 or newer, JUnit Jupiter 5.7.1 (the version in the Gradle user guide example) and Mockito mockito-core 5.24.0.

How the pieces fit: Gradle's test task runs your compiled test classes in a separate JVM and collects the results. The Java plugin creates the test source set and the testImplementation and testRuntimeOnly configurations for you. You only add dependencies and tell the task to use the JUnit Platform.

Gradletest taskJUnit 5 testOrderServiceTestOrderService(real code)PriceRepository(Mockito mock)Resultspassed or failedcallsasks pricewhen / verify
The test controls the mock and checks the real OrderService.

The JUnit and Mockito method names in the code below (@Test, assertEquals, mock, when, verify and so on) are not described in the Gradle pages. Check the Mockito javadoc and the JUnit 5 user guide for their full reference.

Step 1 of 9: Create the project folders

Create a folder named order-demo and the standard Java source folders inside it. Gradle's Java plugin looks for production code in src/main/java and tests in src/test/java, so using these paths means you need no extra configuration.

bash
mkdir -p order-demo/src/main/java/example order-demo/src/test/java/example
cd order-demo

Step 2 of 9: Write the build file

Create build.gradle with the Java plugin, a repository and three test dependencies. The Java plugin gives you the test source set and the test task. testImplementation puts JUnit and Mockito on the test classpath. testRuntimeOnly adds the JUnit Platform launcher that Gradle needs to start the tests.

The useJUnitPlatform() call is what switches the test task to JUnit 5. Without it Gradle would find no JUnit 5 tests.

If you prefer the Kotlin DSL or tasks.named, the Gradle user guide chapter on testing shows the same setup in both syntaxes.

groovy
plugins {
    id 'java'
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.7.1'
    testImplementation 'org.mockito:mockito-core:5.24.0'
    testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

test {
    useJUnitPlatform()
    testLogging {
        events "passed", "failed"
    }
}

Step 3 of 9: Define the dependency to be mocked

Create src/main/java/example/PriceRepository.java. This interface stands for something slow or external, such as a database. You declare it as an interface so Mockito can replace it in tests, and so your code does not depend on a real implementation yet.

java
package example;

public interface PriceRepository {
    int findPriceInCents(String sku);
}

Step 4 of 9: Write the class under test

Create src/main/java/example/OrderService.java. It asks the repository for a unit price and multiplies by the quantity. It rejects a quantity below one before touching the repository. Passing the repository through the constructor lets a test hand in a mock.

java
package example;

public class OrderService {
    private final PriceRepository repository;

    public OrderService(PriceRepository repository) {
        this.repository = repository;
    }

    public int totalInCents(String sku, int quantity) {
        if (quantity < 1) {
            throw new IllegalArgumentException("quantity must be at least 1");
        }
        return repository.findPriceInCents(sku) * quantity;
    }
}

Step 5 of 9: Write the first JUnit 5 test with a mock

Create src/test/java/example/OrderServiceTest.java. The @BeforeEach method runs before every test and builds a fresh mock and service, so tests cannot affect each other.

In the first test, when(...).thenReturn(250) tells the mock what to answer. assertEquals checks the result (3 x 250 = 750). verify confirms the service really asked the repository for that SKU.

java
package example;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

class OrderServiceTest {

    private PriceRepository repository;
    private OrderService service;

    @BeforeEach
    void setUp() {
        repository = mock(PriceRepository.class);
        service = new OrderService(repository);
    }

    @Test
    void totalMultipliesPriceByQuantity() {
        when(repository.findPriceInCents("A1")).thenReturn(250);

        assertEquals(750, service.totalInCents("A1", 3));

        verify(repository).findPriceInCents("A1");
    }
}

Step 6 of 9: Run the test

Run gradle test from the project folder. Gradle compiles both source sets, starts a separate JVM, runs the test and prints the result. Running in a separate JVM keeps your tests isolated from the build process.

bash
gradle test

Step 7 of 9: Add a test for invalid input

Add the next two tests inside the OrderServiceTest class, below the first one, and add the two extra imports at the top of the file. assertThrows checks that the exception is raised. verifyNoInteractions proves the repository was never called for bad input.

The second test shows a Mockito default: a mock method you did not set up with when returns a neutral value, which is 0 for an int. That makes the total 0.

java
// Add these imports at the top of the file:
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.verifyNoInteractions;

// Add these methods inside OrderServiceTest:
@Test
void rejectsQuantityBelowOne() {
    assertThrows(IllegalArgumentException.class,
            () -> service.totalInCents("A1", 0));

    verifyNoInteractions(repository);
}

@Test
void unstubbedMockReturnsZero() {
    assertEquals(0, service.totalInCents("UNKNOWN", 5));
}

Step 8 of 9: Run all tests and check the result

Run gradle test again. Your testLogging setting prints each passed test, so you can confirm that all three ran instead of trusting a silent success. If Gradle reports the task as UP-TO-DATE after you changed nothing, that is normal: use gradle test --rerun-tasks to force a fresh run.

bash
gradle test

Step 9 of 9: Break a test on purpose and fix it

Change 750 to 700 in totalMultipliesPriceByQuantity and run gradle test. You should see a failed test and a failed build. Seeing a test fail proves it can detect a bug. Change the value back to 750 and run again to return to green.

bash
gradle test

Expected result

After step 8 the terminal shows each test as passed, followed by a successful build. Exact formatting varies by Gradle version, but it looks like this: ``` OrderServiceTest > totalMultipliesPriceByQuantity() PASSED OrderServiceTest > rejectsQuantityBelowOne() PASSED OrderServiceTest > unstubbedMockReturnsZero() PASSED BUILD SUCCESSFUL ``` After the deliberate change in step 9, the first test is shown as FAILED and the build ends with `BUILD FAILED`. Reverting the value restores the successful build.

Troubleshooting

ProblemLikely causeFix
Gradle runs but reports no tests, or your JUnit 5 tests are not executedThe test task is still using its default framework because useJUnitPlatform() is missing from the test block.Add useJUnitPlatform() inside the test block of build.gradle, as in step 2, and run gradle test again.
Could not resolve org.junit.jupiter:junit-jupiter or org.mockito:mockito-coreNo repository is declared, or the machine cannot reach it.Check that the repositories block contains mavenCentral() and that your network or proxy settings allow Gradle to download dependencies.
Compilation error: package org.junit.jupiter.api does not existThe JUnit dependency was added to the wrong configuration or has a typo.Declare junit-jupiter and mockito-core under testImplementation. Keep tests under src/test/java, not src/main/java.
Tests fail to start with a message about the JUnit Platform launcherThe launcher is missing from the test runtime classpath.Add testRuntimeOnly 'org.junit.platform:junit-platform-launcher' to the dependencies block.
Mockito or the build fails with an unsupported class version or Java version errorThe JDK you run is older than the Mockito release requires.Check the Java requirement in the Mockito documentation for version 5.24.0 and run Gradle with a matching JDK.

Frequently asked questions

Why does Gradle need useJUnitPlatform()?

The Test task supports JUnit, JUnit Platform and TestNG. Calling useJUnitPlatform() tells it to run JUnit 5 tests through the JUnit Platform.

Where do I put JUnit and Mockito dependencies in Gradle?

Use testImplementation for both libraries. Use testRuntimeOnly for the JUnit Platform launcher. The Java plugin ties these configurations to the test task's classpath.

Which Mockito version does this guide use?

It uses mockito-core 5.24.0 with JUnit Jupiter 5.7.1, the version shown in the Gradle user guide example.

How do I run tests in parallel?

The Test task has a maxParallelForks property, which defaults to 1. A value greater than 1 runs test classes in parallel forks. See the Test execution section of the Gradle guide.

Where can I separate slow tests from unit tests?

Gradle describes integration test setups in its testing chapter, and the incubating JVM Test Suite plugin models extra suites with their own dependencies.

Next steps

  • Read the Gradle chapter on test filtering to run a single test class or method.
  • Read the Gradle chapter on test reporting to see the reports Gradle generates.
  • Read the Mockito javadoc to learn argument matchers and other verification options.
  • Read about configuring integration tests, or the JVM Test Suite plugin, to keep slower tests in a separate suite.

References

From Grokem: https://www.grokem.com/programming/how-to-test-java-code-with-junit-5-and-mockito-a-beginners-gradle-project

Finished this article?

How did this strike you?

Be the first to react – it is anonymous.

Community

Questions about this?

Ask in Questions and help and get help from other readers.

Ask a questionBrowse Questions and help

Comments

No comments yet. Share what worked for you, or ask a question.

Keep learning

Picked for this article

Related reading, discussions and learning paths on the same subject.

All in Programming

Learning paths

Learning pathBeginner

Git, tests and delivery

The everyday safety net of a software project: undo mistakes in Git, get out of the three common Git problems, write tests with pytest and run them on every pull request.

4 lessonsabout 43 minStart

Learning pathBeginner

From numbers to decisions

Read an experiment honestly, judge a classifier fairly and show the result clearly: p-values, an A/B test worked end to end, classification metrics, chart choice and dashboards.

5 lessonsabout 25 minStart

Choose what we may use. You can change this at any time with “Privacy choices” at the foot of every page. Details are in the Cookie policy and the Privacy policy.

Strictly necessary

Remembers your theme, the lessons you marked as done and this choice. It stays on your device, tracks nothing and cannot be switched off.

Always on
What exactly is collected, and why

Google Analytics

Collects
The pages you view, your device and browser type, your language, how you reached the site and your approximate location (country and city, worked out from your IP address).
Why
To understand which pages and lessons are used, so we can improve them.
Stored
Two cookies, _ga and _ga_<id>, for up to 2 years. Google acts for us; the data is processed by Google, including outside your country.

Grokem’s own counts

Collects
The pages you open and how long you stay, how far you scroll, where you came from, your device type, browser, screen size, language and time zone. Your IP address is turned into a code that changes every day; it is never stored as it is.
Why
To see how long lessons are read and where readers leave. Not shared with anyone.
Stored
A random visitor ID, a visit ID and the time of your last page view in your browser’s storage (gr_vid, gr_sid, gr_last). No name or email is attached.