每次测试用例方法运行时,JUnit实例化对象



测试用例:

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);
    }
}

从JUnit测试用例调用的类

public class PendingUtil {
    public PendingUtil() {
        try {
            System.out.println("In Const");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

在我的测试用例中,我只创建了对象一次:

    PendingUtil pendingUtil = new PendingUtil();

但是在内部JUnit调用构造函数三次。

为什么会发生这种情况?

您已经用@Test注释了3个方法。来自JUnit API文档的注释:To run the method, JUnit first constructs a fresh instance of the class then invokes the annotated method.

简而言之,整个测试类被实例化了3次,因此,PendingUtil也是如此(从测试类的每个后续实例中实例一次)。

要做你想做的,保持属性定义在它所在的地方,但是在一个用@BeforeClass注释的新方法中分配PendingUtil实例给它。

另外,你可以像vikingsteve建议的那样将属性标记为静态

您可以在@BeforeClass方法中创建pendingUtil

嘿,只是为了更新Junit5,

你可以在@BeforeAllmethod中创建pendingUtil。

或类似如下:

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class PendingTest {
}

只是为了知识的缘故,我们可以做出生命周期。

相反,如果你不希望PendingUtil被调用三次,你可能应该写一个testtil包装器,它可能只是把一个工厂方法放在new PendingUtil()前面,只创建一个实例。

可以将pendingUtil设置为静态

static PendingUtil pendingUtil = new PendingUtil();

最新更新