DEV Community

Cover image for Tests Everywhere - Java
Roger Viñas Alcon
Roger Viñas Alcon

Posted on • Edited on

Tests Everywhere - Java

GitHub logo rogervinas / tests-everywhere

🤠 Tests, Tests Everywhere!

Java testing this simple Hello World with JUnit5, Mockito and AssertJ

Show me the code

Implementation

  1. Create HelloMessage class in HelloMessage.java:
public class HelloMessage {
  public String getText() {
    return "Hello World!";
  }
}
Enter fullscreen mode Exit fullscreen mode

We can create it as a class as Mockito is able to mock final classes.

  1. Same way create HelloConsole class in HelloConsole.java:
public class HelloConsole {
  public void print(String text) {
    System.out.println(text);
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. 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());
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. 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();
  }
}
Enter fullscreen mode Exit fullscreen mode

Test

Following JUnit5 > Writing Tests, Mockito > Stubbing and AssertJ > Core assertions guide guides ...

  1. Test HelloMessage in HelloMessageTest.java:
@Test
void shouldReturnHelloWorld() {
  var message = new HelloMessage();
  assertThat(message.getText()).isEqualTo("Hello World!");
}
Enter fullscreen mode Exit fullscreen mode
  1. 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);
}
Enter fullscreen mode Exit fullscreen mode
  1. Test output should look like:
> Task :test

HelloAppTest > shouldPrintHelloMessage() PASSED

HelloMessageTest > shouldReturnHelloWorld() PASSED

BUILD SUCCESSFUL in 2s
Enter fullscreen mode Exit fullscreen mode

Happy Testing! 💙

Top comments (0)