I guess the title might be a bit confusing, hopefully you'll understand my question after the explanation.
I want to write a JUnit test class in java. I created an empty list in the constructor. Let's say one test method adds an element to that list and returns true if there is 1 element in that list. Another test method just returns true if the list is empty. Do the tests work independently from each other?
CodePudding user response:
It depends on the test framework, version, and settings.
In JUnit 4, a single instance of a class is used to run all tests in the class. That means that yes, the tests remember.
In JUnit 5, by default a new instance is created for every test. That includes parameterized tests - that's the reason why (by default) argument factory methods need to be static, as there is no instance yet to provide the arguments.
You can use @TestInstance(Lifecycle.PER_CLASS)
to change the behaviour to again use a single instance for all tests.
As QBrute said in a comment, tests should work independently. That means that if your test class maintains state, that state should be reset. JUnit 5 uses @BeforeEach
and @AfterEach
for that. Preferably use @BeforeEach
, because then a failure in the state-reset will not lead to another test failing.
So:
@BeforeEach
void initializeList() {
myList = new ArrayList<>();
// now every test has its own fresh list
}