简体   繁体   English

具有可变参数的JUnit参数化测试

[英]JUnit parameterized test with varying parameters

Consider a parameterized JUnit test. 考虑参数化的JUnit测试。 JUnit provides a way to parameterize such a test using a static method: JUnit提供了一种使用静态方法对这种测试进行参数化的方法:

@Parameterized.Parameters
    public static Collection<Object[]> parameters(){
        Object[][] data = new Object[][] { { 1, 11 }, { 2, 22 }, { 3, 33 }, { 4, 44 } };
        return Arrays.asList(data);
    }

However, this is not what I need, because I do not know the parameters at the test class itself. 但是,这不是我所需要的,因为我不知道测试类本身的参数。 The test class should simply be a test class that can be parameterized with a set of parameters. 测试类应该仅仅是一个测试类, 可以用一组参数进行参数化。 I do not want to specify such parameters inside the class itself. 我不想在类本身内部指定此类参数。 Consider I have a lot of such classes in a test suite. 考虑一下我在测试套件中有很多这样的类。

What I want to be able is to parameterizes the whole test suite from external code. 我想要能够从外部代码参数化整个测试套件。 Ie, have some other code that instanciates the suite with a specific set of parameters. 也就是说,还有其他一些代码可以使用一组特定的参数来实例化套件。 The suite itself does not know the parameters with which it will be parameterized. 套件本身不知道将用于参数化的参数。

Eg, I have a test suite X consisting of the test classes A , B , and C . 例如,我有一个由测试类ABC组成的测试套件X All these classes take, eg, a String and an integer in their constructor as their parameters. 所有这些类在其构造函数中均采用例如String和整数作为参数。 Now I want so be able to instanciate X externally (eg, in another test suite) with a specific String s and int i so that it will instanciate A B and C using s and i in their constructors. 现在,我希望能够在外部(例如,在另一个测试套件中)使用特定的String s和int i实例化X ,以便它将在构造函数中使用si实例化A BC

How can this be achieved? 如何做到这一点?

I'm using the JUnitParams package, which adds more abilities to parametrize tests. 我正在使用JUnitParams程序包,该程序包为参数测试增加了更多功能。 One of those abilities, is to specify a separate class that provides the parameters. 这些功能之一就是指定一个单独的类来提供参数。 Take a look at the link, they give a lot of examples, one of them is using an external class. 看一下链接,他们提供了很多示例,其中之一是使用外部类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM