TestExecutionListeners
are a way to externalize reusable code that instruments your tests.
As such, if you implement a TestExecutionListener
you can reuse it across test class hierarchies and potentially across projects, depending on your needs.
On the flip side, a @BeforeClass
method can naturally only be used within a single test class hierarchy.
Note, however, that JUnit also supports Rules: if you implement org.junit.rules.TestRule
you can declare it as a @ClassRule
to achieve the same thing... with the added benefit that a JUnit Rule can be reused just like a Spring TestExecutionListener
.
So it really depends on your use case. If you only need to use the "before class" functionality in a single test class or a single test class hierarchy, then you'd be better off going the simple route of just implementing a @BeforeClass
method. However, if you foresee that you will need the "before class" functionality in different test class hierarchies or across projects, you should consider implementing a custom TestExecutionListener
or JUnit Rule.
The benefit of a Spring TestExecutionListener
over a JUnit Rule is that a TestExecutionListener
has access to the TestContext
and therefore access to the Spring ApplicationContext
which a JUnit Rule would not have access to. Furthermore, a TestExecutionListener
can be automatically discovered and ordered.
Related Resources:
Regards,
Sam (author of the Spring TestContext Framework)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…