在参数化的junit测试用例中运行特定的测试用例

时间:2012-11-06 19:18:27

标签: java junit

我创建了一个参数化的JUnit测试用例。在这个测试用例中,我在Object [] []中定义了测试用例,每行代表一个测试用例,所有测试用例都会一次运行,现在我想要的只是运行一个测试用例。 假设我想运行第3个测试用例,所以我想告诉junit只考虑对象[] []的第2行?有没有办法做到这一点?

感谢您的回复。 感谢

2 个答案:

答案 0 :(得分:1)

不确定您的意思,但有几个选择:

  1. 使用理论代替参数化,您可以将某些测试标记为@Test,将其他测试标记为@Theory
  2. 在测试中使用assume检查适用于测试的参数化值
  3. 使用Enclosed测试运行器并在一个内部类中隔离一些执行Parameterized的测试以及另一个内部类中的其他测试。
  4. Theories blog

    Assume

    Enclosed

答案 1 :(得分:1)

您可以注释掉您不想运行的测试,例如:

    @Parameters
    public static Collection stringVals() {
        return Arrays.asList(new Object[][] {
            //{"SSS"},
            //{""},
            //{"abcd"},
            {"Hello world"}  //only run this
        });
    }

编辑: 如果要根据测试用例运行不同的测试,还可以忽略JUnit 4+中Assume类的一些测试输入。查看this question

示例:

假设您有两个班级Person,并且您想测试他们是否穿着。如果是sex.equals("male"),您想要检查他的clothes列表是否包含trousers,但对于sex.equals("female"),您要检查她是否包含skirt她的clothes列表。

因此,您可以构建类似的测试:

@Parameter(0)
public Person instance;


@Parameters
public static Collection clothes() {
    Person alice = new Person();
    alice.setSex("female");
    alice.addClothes("skirt");
    Person bob = new Person();
    bob.setSex("male");
    bob.addClothes("trousers");
    return Arrays.asList(new Object[][] {
        {alice, "skirt"},
        {bob, "trousers"},
    });
}

@Test
public void testMaleDressed() {
    //Assume: ignore some test input. 
    //Note: Message is error output; when condition is satisfied, the following lines will run, if not: test ignored
    Assume.assumeTrue("Tested person: " + person + "is female, ignore!", instance.getSex().equals("male"));
    assertTrue(person.getClothes().contains("trousers"));
}

@Test
public void testFemaleDressed() {
    //Assume: ignore some test input. 
    //Note: Message is error output; when condition is satisfied, the following lines will run, if not: test ignored
    Assume.assumeTrue("Tested person: " + person + "is male, ignore!", instance.getSex().equals("female"));
    assertTrue(person.getClothes().contains("skirt"));
}

当您运行所有测试时,您将看到

[0]
    - testMaleDressed(ignored)
    - testFemaleDressed(passed)

[1]
    - testMaleDressed(passed)
    - testFemaleDressed(ignored)

没有错误。