具有动态测试数量的 JUnit 测试 [英] JUnit test with dynamic number of tests

查看:31
本文介绍了具有动态测试数量的 JUnit 测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的项目中,我有几个 JUnit 测试,例如从目录中取出每个文件并对其运行测试.如果我在 TestCase 中实现了一个 testEveryFileInDirectory 方法,这将显示为只有一个可能失败或成功的测试.但我对每个单独文件的结果感兴趣.我如何编写 TestCase/TestSuite 以便每个文件都显示为一个单独的测试,例如在 Eclipse 的图形化 TestRunner 中?(为每个文件编写显式测试方法不是一种选择.)

In our project I have several JUnit tests that e.g. take every file from a directory and run a test on it. If I implement a testEveryFileInDirectory method in the TestCase this shows up as only one test that may fail or succeed. But I am interested in the results on each individual file. How can I write a TestCase / TestSuite such that each file shows up as a separate test e.g. in the graphical TestRunner of Eclipse? (Coding an explicit test method for each file is not an option.)

还比较问题 ParameterizedTest 与 Eclipse Testrunner 中的名称.

推荐答案

查看 JUnit 4 中的参数化测试.

Take a look at Parameterized Tests in JUnit 4.

实际上我几天前就这样做了.我会尽力解释...

Actually I did this a few days ago. I'll try to explain ...

首先正常构建您的测试类,就像您只使用一个输入文件进行测试一样.装饰您的课程:

First build your test class normally, as you where just testing with one input file. Decorate your class with:

@RunWith(Parameterized.class)

构建一个构造函数,它接受在每次测试调用中都会改变的输入(在这种情况下可能是文件本身)

Build one constructor that takes the input that will change in every test call (in this case it may be the file itself)

然后,构建一个静态方法,该方法将返回一个Collection 数组.集合中的每个数组都将包含类构造函数的输入参数,例如文件.装饰这个方法:

Then, build a static method that will return a Collection of arrays. Each array in the collection will contain the input arguments for your class constructor e.g. the file. Decorate this method with:

@Parameters

这是一个示例类.

@RunWith(Parameterized.class)
public class ParameterizedTest {

    private File file;

    public ParameterizedTest(File file) {
        this.file = file;
    }

    @Test
    public void test1() throws Exception {  }

    @Test
    public void test2() throws Exception {  }

    @Parameters
    public static Collection<Object[]> data() {
        // load the files as you want
        Object[] fileArg1 = new Object[] { new File("path1") };
        Object[] fileArg2 = new Object[] { new File("path2") };

        Collection<Object[]> data = new ArrayList<Object[]>();
        data.add(fileArg1);
        data.add(fileArg2);
        return data;
    }
}

另请查看此示例

这篇关于具有动态测试数量的 JUnit 测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆