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

问题描述 投票:2回答:5
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);
    }
}

以上是我的测试用例

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

以上是我从JUnit测试用例调用的类。

在我的测试案例中,我曾经在创建的对象上创建过一次。

PendingUtil pendingUtil = new PendingUtil();

但是内部JUnit三次调用构造函数!可能吗?

java junit junit4
5个回答
5
投票

您可以通过pendingUtil方法创建@BeforeClass


14
投票

您已经用@Test注释了3种方法。在此注释的JUnit API doc中:To run the method, JUnit first constructs a fresh instance of the class then invokes the annotated method.

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

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

另外,您可以按照vikingsteve的建议将属性标记为静态。


0
投票

相反,如果您不希望将PendingUtil调用三次,则可能应该编写一个TestUtil包装器,该包装器可能只是将Factory方法放在new PendingUtil()前面,并且仅创建一个实例。


0
投票

您可以使endingUtil保持静态

static PendingUtil pendingUtil = new PendingUtil();

0
投票

嘿,仅用于Junit5更新,

您可以在@BeforeAllmethod中创建endingUtil。

或如下所示:

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

仅出于知识的考虑,如果我们需要为每个方法创建新的实例,我们都可以创建Lifecycle.PER_METHOD。

© www.soinside.com 2019 - 2024. All rights reserved.