Junit5: Allow non-static methods to be annotated by @BeforeAll and @AfterAll

Created on 11 Aug 2016  路  4Comments  路  Source: junit-team/junit5

According to documentation methods annotated by @BeforeAll and @AfterAll must be static.

TestNG equivalents @BeforeClass and @AfterClass do not have such restriction.

We usually use Spring in our tests so static methods are not much helpful as we cannot work with injected beans.

Even without Spring, I don't like if framework forces me to write static methods.

If possible, allow both static (for backward compatibility) and non-static methods to be annotated by @BeforeAll and @AfterAll.

duplicate

Most helpful comment

@ondrejlerch,

We usually use Spring in our tests so static methods are not much helpful as we cannot work with injected beans.

That is no longer true with the JUnit Jupiter extension model in JUnit 5.

With JUnit Jupiter a static @BeforeAll method can accept parameters which can be beans from a Spring ApplicationContext. SpringExtensionTests demonstrates how this works for @Test methods, but the same holds true for constructors as well as @BeforeAll, @BeforeEach, @AfterEach, and @AfterAll methods.

All 4 comments

I believe this is due to how junit5 instantiate test classes.
I remember at some point, there was @TestInstance.PER_CLASS and @TestInstance.PER_METHOD.

TestNG does PER_CLASS instantiation that's why [Before|After]Class can be non-static. (if I remember its code correctly)

I think per method to be default is fine, but I prefer per class option to be available.
So that, @[Before|After]All can be non-static.
It gives test author to leverage interaction with test instance once per test class.

@ondrejlerch, as you can see, #419 has almost the exact same title as the issue, and its content is identical in purpose.

So, for future reference, please search existing issues before creating a new issue.

Thanks!

Closing this issue since it is a duplicate of #419.

@ondrejlerch,

We usually use Spring in our tests so static methods are not much helpful as we cannot work with injected beans.

That is no longer true with the JUnit Jupiter extension model in JUnit 5.

With JUnit Jupiter a static @BeforeAll method can accept parameters which can be beans from a Spring ApplicationContext. SpringExtensionTests demonstrates how this works for @Test methods, but the same holds true for constructors as well as @BeforeAll, @BeforeEach, @AfterEach, and @AfterAll methods.

Was this page helpful?
0 / 5 - 0 ratings