Should I initialize class fields at declaration like this?
public class SomeTest extends TestCase
{
private final List list = new ArrayList();
publi
In JUnit 4:
final, exactly as stated in the question,@Before, to catch failures.@BeforeClass, but be careful of dependencies between tests.Initializing in a @Before method or test method allows you to get better error reporting on failures. This is especially useful for instantiating the Class Under Test (which you might break), but is also useful for calling external systems, like filesystem access ("file not found") or connecting to a database ("connection refused").
It is acceptable to have a simple standard and always use @Before (clear errors but verbose) or always initialize in declaration (concise but gives confusing errors), since complex coding rules are hard to follow, and this isn't a big deal.
Initializing in setUp is a relic of JUnit 3, where all test instances were initialized eagerly, which causes problems (speed, memory, resource exhaustion) if you do expensive initialization. Thus best practice was to do expensive initialization in setUp, which was only run when the test was executed. This no longer applies, so it is much less necessary to use setUp.
This summarizes several other replies that bury the lede, notably by Craig P. Motlin (question itself and self-answer), Moss Collum (class under test), and dsaff.