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.
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.
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.
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.
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.
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.
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.
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.
// 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.
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.
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
| Problem | Likely cause | Fix |
|---|---|---|
| Gradle runs but reports no tests, or your JUnit 5 tests are not executed | The 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-core | No 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 exist | The 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 launcher | The 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 error | The 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








