Junit 5 Examples

Published: 2020-05-14, Updated: 2020-05-18

Check if exception was thrown, then check the message

import static org.junit.jupiter.api.Assertions.assertThrows;

@Test
void exceptionTesting() {
    MyException thrown = assertThrows(
           MyException.class,
           () -> myObject.doThing(),
           "Expected doThing() to throw, but it didn't"
    );

    assertTrue(thrown.getMessage().contains("Stuff"));
}

Save state between tests executions

@Override
public void beforeAll(ExtensionContext context) throws Exception {
  final Store store = context
    .getRoot()
    .getStore(ExtensionContext.Namespace.GLOBAL);

  if (store.get(EmbeddedPostgres.class.getName(), EmbeddedPostgres.class) == null) {
    store.put(EmbeddedPostgres.class.getName(), new EmbeddedPostgres())
  }
}

awesome junit 5, junit 5 commands


Run lua on top of JavaScript The Clean Code

Comments