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

Java 如何使用不同的参数运行选定的junit测试,java,junit,customization,parameterized,Java,Junit,Customization,Parameterized,我想从任何具有不同参数的测试类运行选定的测试方法 例: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("Fro

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

例: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) 使用不同参数“test1”和“test2”测试两次(来自ClassA)
2) testC(来自ClassB)两次,带有不同的参数“test3”和“test3”

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


有人能帮上忙吗…

尝试使用JUnit参数化测试。以下是一份:

JUnit4引入了一个名为参数化测试的新特性。参数化测试允许开发人员使用不同的值反复运行相同的测试。创建参数化测试需要遵循五个步骤

  • 用@RunWith(参数化的.class)注释测试类

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

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

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

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

测试用例将为每一行数据调用一次


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

请参阅(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;
   }
}
@RunWith(参数化的.class)
公共类遗嘱{
@Parameterized.Parameters(name=“{index}:methodA({1})”)
公共静态可编辑数据(){
返回Arrays.asList(新对象[][]{
{“来自test1”,“test1”},{“来自test2”,“test2”}
});
}
私有字符串实际值;
应为私有字符串;
公共测试(预期字符串,实际字符串){
this.expected=expected;
this.actual=实际;
}
@试验
公开无效测试(){
String actual=methodFromA(this.actual);
资产质量(预期、实际);
}
私有字符串方法FromA(字符串输入){
返回“来自”+输入;
}
}
您可以为类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);
    }
}
@RunWith(参数化的.class)
公共类测试单元{
/**
*提供Iterable以列出单个参数
*/
@参数

公共静态iTerable您是如何运行测试的。您是使用IDE还是Maven之类的构建工具?这也是正确答案。需要在参数化方法中为动态参数编写代码并分配给数组。