Skip to content
Advertisement

JUnit instantiating object every time a test case method runs

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?

Advertisement

Answer

You could create the pendingUtil in a @BeforeClass method.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement