I'm using a JUnit 4 test case and I want to use the @AfterClass
annotation. To use it, the method using it must be static. And inside this very method, I want to use my @Inject
ed objects.
But seems they cannot be static, i.e. they are null during runtime of the test if they are static. Actually, I want to delete certain database objects after all my tests have been run and I don't want to use @After
.
How can I solve this problem? The only thing I can think of is to run the test cases alphabetically and make zzz()
apply the logic I want.
Not using Spring, using Arquillian and deploying an ear to the server when testing
Firstly: database-involved unit testing is not so trivial, due to completely different nature unit tests (being independent of each other by definition) and databases (being inherently stateful).
Your approach with deleting certain database objects after all tests is generally not recommended.
In most cases far better approach is to:
To achieve above goals there are some tools. One is excellent Arquillian Persistence Extension for database population. And another is DbSetup (this is my favourite).
Also alternative exists
If using additional tool is not an option for you, then you should know that Arquillian’s JUnit integration provides an handy @InSequence
annotation that can be used to set an explicit order of tests execution.
@Test
@InSequence(1)
public void place_order_should_add_order() {
// some logic here
}
@Test
@InSequence(2)
public void order_should_be_persistent() {
// some logic here that depends on the previous test-case
}
This is far better than relying on the alphabetical order of the names of methods.
Also please note that above methods are not static, so you can use inside them whatever objects injected by the container - like DataSource
or EntityManager
etc.