在 JUnit 测试用例中使用不同的数据子集测试不同的方法

Test different methods with different subset of data in JUnit test case

假设我有一个 JUnit 测试用例:

@RunWith(Parameterized.class)
public class TestMyClass {

    @Parameter
    private int expected;
    @Parameter
    private int actual;  

    @Parameters
    public static Collection<Object[]> data() {
    return Arrays.asList(new Object[][] {     
             { 0,1 }, { 1,2 }, { 2,3 }, { 3,4 }, { 4,5 }, { 5,6 },{ 6,7 }  
       });
    }

    @Test
    public void test1 { //test }

    @Test
    public void test2 { //test }

}

我只想 运行 test1 仅使用 {0,1}、{1,2} 和 {2,3} 和 运行 test2 只有 {3,4}, {4,5} {5,6}

我怎样才能做到这一点?

编辑:参数在运行时从文件中读取。

似乎无法使用 JUnit standart '@Parameters' 一次性使用不同的参数集进行不同的测试 class。 你可以试试junit-dataprovider。它类似于 TestNG 数据提供者。 例如:

@RunWith(DataProviderRunner.class)
public class TestMyClass {

    @DataProvider
    public static Object[][] firstDataset() {
    return new Object[][] {     
             { 3,4 }, { 4,5 }, { 5,6 },{ 6,7 }  
       };
    }


    @DataProvider
    public static Object[][] secondDataset() {
    return new Object[][] {     
             { 3,4 }, { 4,5 }, { 5,6 },{ 6,7 }  
       };
    }

    @Test
    @UseDataProvider("firstDataset")
    public void test1(int a, int b) { //test }

    @Test
    @UseDataProvider("secondDataset")
    public void test2(int a, int b) { //test }

}

或者您可以为每个测试创建 2 个 classes。

不过我觉得用junit-dataprovider更方便

有很多 junit 库可以让您这样做。如果您预先知道参数(看起来像您的情况),parametrized testing with zohhak 可能是最简单的:

@RunWith(ZohhakRunner.class)
public class TestMyClass {      

    @TestWith({
        "1, 6".
        "2, 8",
        "3, 4"
    })
    public void test1(int actual, int expected) { //test }

    @TestWith({
        "2, 2".
        "0, -8",
        "7, 1"
    })
    public void test2(int actual, int expected) { //test }

}

如果您需要在 运行 时间内构建参数(生成、从文件中读取等),那么您可以检查 junit-dataprovider or junit-params

之类的内容

如果不想使用其他库,可以使用 JUnit 的 Enclosed 运行程序:

@RunWith(Enclosed.class)
public class ATest {

  @RunWith(Parameterized.class)
  public static class TestMyClass {

    @Parameter
    private int expected;
    @Parameter
    private int actual;  

    @Parameters
    public static Collection<Object[]> data() {
      return Arrays.asList(new Object[][] {     
         { 0,1 }, { 1,2 }, { 2,3 }  
      });
    }

    @Test
    public void test1 {
      //test
    }
  }

  @RunWith(Parameterized.class)
  public static class TestMyClass {
    @Parameter
    private int expected;
    @Parameter
    private int actual;  

    @Parameters
    public static Collection<Object[]> data() {
      return Arrays.asList(new Object[][] {     
         { 3,4 }, { 4,5 }, { 5,6 },{ 6,7 }  
      });
    }

    @Test
    public void test2 {
      //test
    }
  }
}

顺便说一句:在 JUnit 4.12 中,您不必使用 List 来包装参数。

@Parameters
public static Object[][] data() {
  return new Object[][] {     
     { 0,1 }, { 1,2 }, { 2,3 }  
  };
}