JUnit instantiating object every time a test case method runs

10,041

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.

Share:
10,041
voldy
Author by

voldy

Java , Flex , Spring , Hibernate , IBM Filenet, Oracle

Updated on June 26, 2022

Comments

  • voldy
    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
    Mark Tielemans almost 11 years
    That seems needlessly complicated. Alternative could be to make the property static and treat it as a singleton instance in a @Before method.
  • Keppil
    Keppil almost 11 years
    It would have to be static then, so you might as well initialize it where it is done now.
  • rajah9
    rajah9 almost 11 years
    +1 and the documentation may be found at junit.sourceforge.net/javadoc/org/junit/BeforeClass.html
  • Mark Tielemans
    Mark Tielemans almost 11 years
    No, you are right, of course. I removed the comment because it was obviously false. Thanks for notifying!