Reputation: 51
What is the proper way with JUnit 4 to create test cases to use common functionality: e.g. setup that is common to several unit test classes? What I did was create a test case and put the common functionality in the @Before
method, then any test case that needs this would extend the base class. However, this seems to require doing: super.setUp()
in every subclass.
Is there a better way?
EDIT
Actually my proposed solution is not working. Sometimes JUnit will call the base class TWICE. Once if it happens to run the test on the base class first, and again when it reaches a child class (at least I think this is whats happening). So a better way of "inheriting" common test case functionality would be great.
Upvotes: 5
Views: 2158
Reputation: 2311
If your base class has a method public void setUp(), and so does your sub-class, then the sub-class's setUp method overrides the base class's method of the same name and signature, so only the sub-class's method will be called (and it may be called when the base class's method should have been called; not sure about this).
The solution is to call your base class setup method something else, e.g. baseSetup(). Then they will both be called automatically. Joachim's answer does address the naming, but I wanted to be clearer about the effects of method override.
Upvotes: 0
Reputation: 18714
You don't need to invoker super.setup()
if you use the @Before
annotation:
When writing tests, it is common to find that several tests need similar objects created before they can run. Annotating a public void method with
@Before
causes that method to be run before the Test method. The@Before
methods of superclasses will be run before those of the current class.
I'd suggest something like this:
@Before
public void initForAll() {}
In the super/Main class
and any
@Before
public void initTest() {...}
In your Testcases.
EDIT:
To answer your questions in the edit.
@BeforeClass
which will be invoked once per TestClass. I do this like this:
private boolean initialized = false;
@BeforeClass
public static void init()
{
if(initialized)
{
return;
}
//Initialize everything
initialized = true;
}
Upvotes: 5
Reputation: 2169
Have you tried other approach. Instead of creating a base class with a common functionality, make an util class with static methods which will the common functionality. Then just call util methods in @Before annotated method of each test case.
Upvotes: 0
Reputation: 120268
thats a pretty good way to do it. If you have a setUp()
on the subclass, then yes, you have to invoke super.setUp()
, but really, how hard is that?
Upvotes: 0