JUnit instantiating object every time a test case method runs
Solution 1
You could create the pendingUtil
in a @BeforeClass
method.
Solution 2
You've annotated 3 methods with @Test
. From the JUnit API doc on this annotation: To run the method, JUnit first constructs a fresh instance of the class then invokes the annotated method.
In short, the entire test class is instanced 3 times, and therefore, so is PendingUtil
(once from each subsequent instance of the test class).
To do what you want, keep the property definition where it is, but assign the PendingUtil
instance to it in a new method annotated with the @BeforeClass annotation.
Additionally, you could mark the property as static as suggested by vikingsteve.
Comments
-
voldy almost 2 years
Test case:
import static org.junit.Assert.assertTrue; import org.junit.Test; public class PendingTest { PendingUtil pendingUtil = new PendingUtil(); boolean result; @Test public void fetchPendingWFFromDB(){ result = pendingUtil.fetchPendingWFFromDB(); assertTrue(result); } @Test public void runPendingBatch() { result = pendingUtil.runPendingBatch(); assertTrue(result); } @Test public void checkQueuePostPendingRun() { result = pendingUtil.checkQueuePostPendingRun(); assertTrue(result); } }
Class called from JUnit test case.
public class PendingUtil { public PendingUtil() { try { System.out.println("In Const"); } catch (SQLException e) { e.printStackTrace(); } } }
In my test case I only create the object once:
PendingUtil pendingUtil = new PendingUtil();
But internally JUnit calls the constructor three times.
Why is this happening?
-
Mark Tielemans almost 11 yearsThat seems needlessly complicated. Alternative could be to make the property static and treat it as a singleton instance in a
@Before
method. -
Keppil almost 11 yearsIt would have to be
static
then, so you might as well initialize it where it is done now. -
rajah9 almost 11 years+1 and the documentation may be found at junit.sourceforge.net/javadoc/org/junit/BeforeClass.html
-
Mark Tielemans almost 11 yearsNo, you are right, of course. I removed the comment because it was obviously false. Thanks for notifying!