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

vol*_*ldy 2 java junit junit4

package com.bnpparibas.test;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import com.bnpparibas.util.PendingUtil;

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

以上是我的测试用例

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

上面是我从JUnit测试用例调用的类.

在我的测试用例中,我有一次创建对象..

PendingUtil pendingUtil = new PendingUtil();
Run Code Online (Sandbox Code Playgroud)

但内部JUnit调用构造函数三次!这是可能的.

Mar*_*ans 13

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

简而言之,整个测试类实例化3次,因此PendingUtil(从测试类的每个后续实例开始).

要执行所需操作,请将属性定义保留在原始位置,但PendingUtil在使用@BeforeClass批注注释的新方法中将实例分配给它.

此外,您可以将该属性标记为vikingsteve建议的静态.


The*_*Cat 5

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

  • 它必须是"静态"然后,所以你不妨在现在完成它的地方进行初始化. (2认同)
  • +1和文档可以在http://junit.sourceforge.net/javadoc/org/junit/BeforeClass.html找到 (2认同)