views:

60

answers:

4

I understand in Junit 4, @Before can be used to setup test fixtures for the test class's multiple test methods.

However, in my system, there are common test objects i would like to have available for all tests.

What is the most appropriate name for these objects and what is a good best practice way to store them?

A: 

The preferred names for your common test objects will depend on what these objects really are (I can't help unless you provide more detail). If you want to share an object between all the tests then it must be static in your test class (JUnit will recreate the test class before every test).

Grzenio
+3  A: 

The best practice is to create them in the fixture so as to keep the tests isolated, unless their state is not changed by the tests (such as a logger). Otherwise one may have side-effects between the tests: one test failing because of another one, or the opposite.

philippe
+1  A: 

There is definitely a use case for having some shared data between test cases. JUnit provides the @BeforeClass annotation for this. Should help you I hope...

http://junit.sourceforge.net/javadoc/org/junit/BeforeClass.html

Java Drinker
Note that any BeforeClass methods have to be static. This may not be an issue but it may cause you to have a mix of static and non-static members in the class. Not a huge deal, but maybe not the cleanest code.
AngerClown
A: 

Why not have an abstract BaseTest superclass that holds the common objects and initializes them, either in the constructor or a @BeforeClass method?

AngerClown