如何 运行 选择具有不同参数的 junit 测试

How to run selected junit tests with different parameters

我想运行从具有不同参数的任何测试class中选择测试方法

例如:1) A 类 -> 测试方法 A、B

@Test
public void testA(String param) {
    System.out.println("From A: "+param);
}
@Test
public void testB(String param) {
}

2) B 类 -> 测试方法 C、D

@Test
public void testC(String param) {
    System.out.println("From C: "+param);
}
@Test
public void testD(String param) {
}

根据这些,我想 运行 进行以下测试
1) testA(from ClassA) 两次 diff params "test1" & "test2"
2) testC(from ClassB) 两次 diff params "test3" & "test3"

此处我的测试计数应显示为“4”

任何人都可以帮忙...

尝试使用 JUnit 参数化测试。这是一个 tutorial from TutorialsPoint.com:

JUnit 4 has introduced a new feature called parameterized tests. Parameterized tests allow a developer to run the same test over and over again using different values. There are five steps that you need to follow to create a parameterized test.

  • Annotate test class with @RunWith(Parameterized.class).

  • Create a public static method annotated with @Parameters that returns a Collection of Objects (as Array) as test data set.

  • Create a public constructor that takes in what is equivalent to one "row" of test data.

  • Create an instance variable for each "column" of test data.

  • Create your test case(s) using the instance variables as the source of the test data.

The test case will be invoked once for each row of data.

使用 Junits 提供的参数化测试,其中您可以在 运行 时间传递参数。

参考org.junit.runners.Parameterized(JUnit 4.12 提供了在设置数组中使用预期值和不使用预期值进行参数化的可能性)。

试试这个:

@RunWith(Parameterized.class)
public class TestA {

   @Parameterized.Parameters(name = "{index}: methodA({1})")
   public static Iterable<Object[]> data() {
      return Arrays.asList(new Object[][]{
            {"From A test1", "test1"}, {"From A test2", "test2"}
      });
   }

   private String actual;
   private String expected;

   public TestA(String expected,String actual) {
      this.expected = expected;
      this.actual = actual;
   }

   @Test
   public void test() {
      String actual = methodFromA(this.actual);
      assertEquals(expected,actual);
   }

   private String methodFromA(String input) {
      return "From A " + input;
   }
}

您可以为 class B 编写类似的测试。

对于仅采用单个参数的测试,对于 JUnit 4.12,您可以这样做:

@RunWith(Parameterized.class)
public class TestU {

    /**
     * Provide Iterable to list single parameters
     */

    @Parameters
    public static Iterable<? extends Object> data() {
        return Arrays.asList("a", "b", "c");
    }

    /**
     * This value is initialized with values from data() array
     */

    @Parameter
    public String x;

    /**
     * Run parametrized test
     */

    @Test
    public void testMe() {
        System.out.println(x);
    }
}