Java Unit Testing - constant fields versus setUp()

java, junit, unit-testing

Solution

Using the setup method will cause the initialization code to run before each test. Static initializers will run once (and only once) when the class is first loaded, which means they will execute only once per test run.

It is often a better idea to initialize everything fresh for each test, just to remove the ability of the state of any objects from one test affecting other tests.

The only time I have found using static initialization to be useful was when I was writing integration (not unit) tests and my class under test was expensive to construct. I was certain that the object was stateless though so that tests could not interfere with each other. If you aren't certain, it is better to use the setup() method to be safe.

Problem

I am writing a test class for an implementation of an interface, and want to test my implementation against another implementation (i.e. to ensure consistency). The test methods will then test each of the interface methods to check this. To do this I could: a) create a `private static` constant fields of the original implementation and my new implementation: ``` public class MyImplTest extends TestCase { private static OldImpl _original; private static MyImpl _myImpl; static { // instantiate _original and _myImpl } // My tests } ``` b) create `private` fields of the two implementations, and instantiate them using `setUp()`: ``` public class MyImplTest extends TestCase { private OldImpl _original; private MyImpl _myImpl; public void setUp(){ // instantiate _original and _myImpl } // My tests } ``` Is either of these preferred / considered good style? My instinct suggests (b), but I want to create quite large objects, and `setUp()` gets run for each `testSomething()` method in the `TestCase`, so both `_original` and `_myImpl` would be created multiple times. FWIW, I'm using JUnit 3.

Original source

Related problems