JUnit: new instance before invoking each @Test method. What are the benefits?

How to see the real benefits of the approach described in the book?

The purpose of separate instance is not for any benefit but to maintain the contract that each test should be independently executed without any effect of the execution of a previous test. There is just no other way to ensure this contract other than using a different instance for each test.

For example, the Spring transaction management makes sure to rollback all changes made to the database by a test, by default, to maintain the same contract.

So, using static variables in a test is generally discouraged as it will defeat the whole purpose of one-instance-per-test to have a clean slate for each test.

Leave a Comment