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.