Search code examples
javajunitjunit5

junit 5 code/configuration reuse. should i use abstract test class or an extension?


junit 5 docs is using AbstractDatabaseTests

but i remember recommended way for junit 4 was to use rules rather than extending classes.


Solution

  • The example using an AbstractDatabaseTest is there to demonstrate that "JUnit Jupiter also [in addition to registered extensions] guarantees wrapping behavior within class and interface hierarchies […]".

    From the user guide:

    JUnit Jupiter is the combination of the programming model and extension model for writing tests […]

    Extensions are a core JUnit Jupiter feature and are considered more idiomatic than using inheritance.

    While JUnit Jupiter also supports inheritance (many annotations are @Inherited), the extensions mechanism follows the principle of composition over inheritance. This gives you, for instance, more flexibility as you can use multiple extensions, whereas inheritance is limited to a single class.