rogervinas / tests-everywhere
🤠 Tests, Tests Everywhere!
Java testing this simple Hello World with JUnit5, Mockito and AssertJ
Show me the code
Implementation
- 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();
}
}
Test
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
Happy Testing! 💙
Top comments (0)