如何使用不同的参数运行选定的junit测试

kvy*_*ysh 4 java customization junit parameterized

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

例如:1)ClassA - >测试方法A,B

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

2)ClassB - >测试方法C,D

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

从这些我希望运行以下测试
1)testA(来自ClassA)两次使用diff params"test1"和"test2"
2)testC(来自ClassB)两次使用diff params"test3"和"test3"

这里我的测试计数应该显示为'4'

任何人都可以帮助...

小智 13

使用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;
   }
}
Run Code Online (Sandbox Code Playgroud)

你可以为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);
    }
}
Run Code Online (Sandbox Code Playgroud)


ami*_*ith 6

尝试使用 JUnit 参数化测试。这是来自 TutorialsPoint.com 的教程

JUnit 4 引入了一个称为参数化测试的新特性。参数化测试允许开发人员使用不同的值一遍又一遍地运行相同的测试。创建参数化测试需要遵循五个步骤。

  • 使用@RunWith(Parameterized.class) 注释测试类。

  • 创建一个用@Parameters 注释的公共静态方法,该方法返回一个对象集合(作为数组)作为测试数据集。

  • 创建一个公共构造函数,它接收相当于一“行”测试数据的内容。

  • 为测试数据的每个“列”创建一个实例变量。

  • 使用实例变量作为测试数据的来源创建您的测试用例。

测试用例将针对每一行数据调用一次。