What's the purpose of the JUnit 5 @Nested annotation

前端 未结 4 1695
故里飘歌
故里飘歌 2021-02-18 21:14

In JUnit 5, there is a new annotation: @Nested.

I understand how it work, I understand why we use nested class, I just don\'t understand why we need to have

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-18 21:58

    All my tests need a database server running. Most of my tests also need a Users table in the database, to be able to log in. In addition to that, some tests need the Friends table, to be able to login and query friends.

    Each resource has a setup and teardown. I have to start and stop server, create and delete tables.

    With the @Nested annotation, I can group my tests in a hierarchy of nested classes so that every test gets the setup and teardown of all tests up the hierarchy.

    This idea of nesting tests was popularized in Ruby. In Java is implemented for Junit 4 by the HierarchicalContextRunner. See the justification on its page https://github.com/bechte/junit-hierarchicalcontextrunner/wiki.

提交回复
热议问题