Java testing with JUnit5, Mockito and AssertJ
- Create
HelloMessage
class in HelloMessage.java:
public class HelloMessage {
public String getText() {
return "Hello World!";
}
}
We can create it as a class as Mockito is able to mock final classes.
- Same way create
HelloConsole
class in HelloConsole.java:
public class HelloConsole {
public void print(String text) {
System.out.println(text);
}
}
- Create
HelloApp
class in HelloApp.java:
public class HelloApp {
private final HelloMessage message;
private final HelloConsole console;
public HelloApp(HelloMessage message, HelloConsole console) {
this.message = message;
this.console = console;
}
public void printHello() {
console.print(message.getText());
}
}
- Create main class in Main.java that wraps it all together:
public class Main {
public static void main(String[] args) {
var message = new HelloMessage();
var console = new HelloConsole();
var app = new HelloApp(message, console);
app.printHello();
}
}
Following JUnit5 > Writing Tests, Mockito > Stubbing and AssertJ > Core assertions guide guides ...
- Test
HelloMessage
in HelloMessageTest.java:
@Test
void shouldReturnHelloWorld() {
var message = new HelloMessage();
assertThat(message.getText()).isEqualTo("Hello World!");
}
- Test
HelloApp
in HelloAppTest.java:
@Test
void shouldPrintHelloMessage() {
var messageText = "Hello Test!";
// 2.1 Create a mock of HelloMessage
var message = mock(HelloMessage.class);
// 2.2 Return "Hello Test!" whenever getText() is called
when(message.getText()).thenReturn(messageText);
// 2.2 Create a mock of HelloConsole
var console = mock(HelloConsole.class);
// 2.3 Create a HelloApp, the one we want to test, passing the mocks
var app = new HelloApp(message, console);
// 2.4 Execute the method we want to test
app.printHello();
// 2.5 Verify HelloConsole mock print() method
// has been called once with "Hello Test!"
verify(console).print(messageText);
}
- Test output should look like:
> Task :test
HelloAppTest > shouldPrintHelloMessage() PASSED
HelloMessageTest > shouldReturnHelloWorld() PASSED
BUILD SUCCESSFUL in 2s
Run this project using 🐳 docker
- Execute
./docker-run.sh
- Once inside the container:
- Test with
./gradlew test --rerun-tasks
- Run with
./gradlew run
- Test with
- Install Java and Gradle manually or ...
- Install SdkMan and ...
- List available versions executing
sdk list java
andsdk list gradle
- Install Java executing
sdk install java 21-tem
- Install Gradle executing
sdk install grade 8.4
- List available versions executing
- Install SdkMan and ...
- Test with
./gradlew test --rerun-tasks
- Run with
./gradlew run
- Create project using
gradle init --type java-application --dsl kotlin --test-framework junit-jupiter
- Add Mockito and AssertJ dependencies in build.gradle.kts:
dependencies { testImplementation("org.mockito:mockito-core:x.x.x") testImplementation("org.assertj:assertj-core:x.x.x") }