Common Notes

  • Test classes and methods need not to be public but can be package private.
    • Reduces unwanted visibility of classes and methods, useful e.g. in Eclipse.
  • Can have nested test classes.
    • Helps to structure test classes.

Grouping Tests

Grouping of test classes:

JUnit Jupiter @Nested annotation

See https://junit.org/junit5/docs/current/api/org/junit/jupiter/api/Nested.html

@Nested is used to signal that the annotated class is a nested, non-static test class (i.e., an inner class) that can share setup and state with an instance of its enclosing class. The enclosing class may be a top-level test class or another @Nested test class, and nesting can be arbitrarily deep.

  • Group test methods for feature / methods
  • Can share state and initialization with outer class
  • Grouping of test classes can be
    • Test class per class
    • Nested test class per method / feature

A nice example is https://github.com/apache/commons-lang/blob/master/src/test/java/org/apache/commons/lang3/ValidateTest.java

Static Nested Test Classes

See discussion https://github.com/junit-team/junit5/issues/69

  • Treated like top-level class.

Assertions

See https://junit.org/junit5/docs/current/user-guide/#writing-tests-assertions

  • Methods of class org.junit.jupiter.api.Assertions

Can also use Hamcrest http://hamcrest.org/JavaHamcrest/index with the org.hamcrest.MatcherAssert.assertThat(...) methods. Background: https://objectpartners.com/2013/09/18/the-benefits-of-using-assertthat-over-other-assert-methods-in-unit-tests/

References