views:

27

answers:

1

Is there any reason to put object creation inside of setUp() rather than at an instance variable declaration?

I've seen it done this way in books, but the effect is the same and I'm not sure if it was done for a best practice reason, because an earlier version of Junit did not instantiate the object for each test (see here), or if it's just a style thing.

+3  A: 

If the instantiation of the object in question does not depend on external factors, it is perfectly OK to declare and define it at once. However, often it depends on other factors (e.g. initialization of a singleton*), or requires constructor parameters - some of which may even be test-dependent -, or its initialization takes multiple steps. Then you have to defer instantiation to the setup method, or even to the test method itself.

Note that JUnit creates a new instance of the test class, thus a new instance of its data members for each test method execution anyway. So if you have none of the dependencies mentioned above, semantically there is no difference between instantiating a member at the point of declaration or in the setup method.

*this is one of the reasons Singletons are not liked. However, often you still have them, especially in legacy code.

Péter Török
thank you, this makes sense
orbfish