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

Java 在参数化junit测试用例中运行特定测试用例,java,junit,Java,Junit,我创建了一个参数化的JUnit测试用例。在这个测试用例中,我在对象[][]中定义了测试用例,每一行代表一个测试用例,所有测试用例都将一次运行,现在我想要的是一种只运行一个测试用例的方法。 假设我想运行第三个测试用例,所以我想告诉JUnit只考虑对象的第二行[][]。有办法吗 感谢您的回复。 谢谢我不知道你的意思,但有几个选择: 使用理论而不是参数化,这样您可以将一些测试标记为@Test,将其他测试标记为@Theory 在测试中使用假设,检查应用于测试的参数化值 使用附带的测试运行程序,在一个内部

我创建了一个参数化的JUnit测试用例。在这个测试用例中,我在对象[][]中定义了测试用例,每一行代表一个测试用例,所有测试用例都将一次运行,现在我想要的是一种只运行一个测试用例的方法。 假设我想运行第三个测试用例,所以我想告诉JUnit只考虑对象的第二行[][]。有办法吗

感谢您的回复。
谢谢

我不知道你的意思,但有几个选择:

  • 使用理论而不是参数化,这样您可以将一些测试标记为
    @Test
    ,将其他测试标记为
    @Theory
  • 在测试中使用
    假设
    ,检查应用于测试的参数化值
  • 使用
    附带的
    测试运行程序,在一个内部类中隔离一些进行
    参数化
    的测试,并在另一个内部类中隔离其他测试

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

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

    编辑: 如果您想根据测试用例运行不同的测试,还可以使用JUnit4+中的
    aspect
    class忽略一些测试输入。检查

    例如:

    假设您有两个class
    Person
    的实例,您想测试它们是否穿着衣服。如果是
    sex.equals(“男”)
    ,你要检查他的
    衣服
    列表是否包含
    裤子
    ,但是对于
    sex.equals(“女”)
    ,你要检查她的
    衣服列表中是否包含
    裙子

    因此,您可以像这样构建测试:

    @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)
    

    没有错误。

    您的独立示例在哪里?