Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Do tests "remember"? independency

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading