Java – Best Practice: Initialize JUnit class fields in setUp() or at declaration

javajunit

Should I initialize class fields at declaration like this?

public class SomeTest extends TestCase
{
    private final List list = new ArrayList();

    public void testPopulateList()
    {
        // Add stuff to the list
        // Assert the list contains what I expect
    }
}

Or in setUp() like this?

public class SomeTest extends TestCase
{
    private List list;

    @Override
    protected void setUp() throws Exception
    {
        super.setUp();
        this.list = new ArrayList();
    }

    public void testPopulateList()
    {
        // Add stuff to the list
        // Assert the list contains what I expect
    }
}

I tend to use the first form because it's more concise, and allows me to use final fields. If I don't need to use the setUp() method for set-up, should I still use it, and why?

Clarification:
JUnit will instantiate the test class once per test method. That means list will be created once per test, regardless of where I declare it. It also means there are no temporal dependencies between the tests. So it seems like there are no advantages to using setUp(). However the JUnit FAQ has many examples that initialize an empty collection in setUp(), so I figure there must be a reason.

Best Answer

If you're wondering specifically about the examples in the JUnit FAQ, such as the basic test template, I think the best practice being shown off there is that the class under test should be instantiated in your setUp method (or in a test method).

When the JUnit examples create an ArrayList in the setUp method, they all go on to test the behavior of that ArrayList, with cases like testIndexOutOfBoundException, testEmptyCollection, and the like. The perspective there is of someone writing a class and making sure it works right.

You should probably do the same when testing your own classes: create your object in setUp or in a test method, so that you'll be able to get reasonable output if you break it later.

On the other hand, if you use a Java collection class (or other library class, for that matter) in your test code, it's probably not because you want to test it--it's just part of the test fixture. In this case, you can safely assume it works as intended, so initializing it in the declaration won't be a problem.

For what it's worth, I work on a reasonably large, several-year-old, TDD-developed code base. We habitually initialize things in their declarations in test code, and in the year and a half that I've been on this project, it has never caused a problem. So there's at least some anecdotal evidence that it's a reasonable thing to do.

Related Topic