【问题标题】:Instantiate a class once per parameter in JUnit在 JUnit 中为每个参数实例化一个类
【发布时间】:2013-07-05 23:30:58
【问题描述】:

所以我正在尝试运行测试来评估不同网站的某些属性。实际评估是由按通话付费的资源处理的,所以我想尽量减少生成资源的次数。此外,我需要它在 JUnit 中运行以适应更大的自动化测试套件。

到目前为止,我一直在使用参数化测试进行此操作,但我刚刚了解到它们会为每个测试方法实例化一个新实例。

现在我正试图找出一种方法,为每个参数创建一次资源,该参数被输入到我的测试类的构造函数中。 @BeforeClass 只执行一次,@Before 在每次测试前执行一次。

我能找到的所有帮助主题都涉及为所有测试创建一次昂贵的资源,但在这种情况下,我需要为每组新参数重新创建资源。

我在下面编写了一些示例代码/输出以更好地显示我正在寻找的内容:

@RunWith(Parameterized.class)
public class MyTestClass {

    private static Resource expensiveToCreateResource;

    public MyTestClass(String url) {
        System.out.println("Constructing resource for " + url);
        expensiveToCreateResource = new Resource(url); //This is getting created 4x, which is wrong
    }

    @Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][] {{"url1"},{"url2"}});
    }

    @Test
    public test1() {
        expensiveToCreateResource.method1();
        System.out.println("test1");
    }

    @Test 
    public test2() {
        expensiveToCreateResource.method2();
        System.out.println("test2");
    }
}

会产生输出:

Constructing resource for url1
test1
test2
Constructing resource for url2
test1
test2

有什么想法/解决方案吗?谢谢。

【问题讨论】:

    标签: junit parameterized


    【解决方案1】:

    如果您想让每个参数实例化一次类,您必须编写自己的 JUnit 测试运行程序。相反,我会尝试根据需要缓存信息,例如在将 URL 映射到资源的静态映射中。

    【讨论】:

      猜你喜欢
      • 2013-01-03
      • 1970-01-01
      • 2012-12-14
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      • 2010-12-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多