首页 > 解决方案 > 仅使用注释使用不同的测试数据运行测试方法多次

问题描述

我想多次运行测试方法,并且在每次测试运行期间,我希望初始化方法使用 RestApiCall.sendRequest() 方法的不同参数运行,例如 a、b、c 和 d。另外我希望测试方法根据传递的参数打印测试名称。

@BeforeaClass
void initialise(){
   ResponseData responsedata = RestApi.sendRequest("a");
}

@Test
void TestApiCall(){
  testResponse(responsedata);
  System.out.println("Passed TestApiCall A");
}

标签: javajunittestngtestng-annotation-test

解决方案


完全有两种方法可以做到这一点。

方法 1:使用数据提供者驱动的工厂

在这里,您有一个@Factory由数据提供者提供支持的,要创建测试类实例,并且在其中,您可以@BeforeMethod执行您需要执行的任何休息调用调用,然后让您的@Test方法与响应一起工作。

这是一个完整的示例,显示了这一点

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;

public class SampleTestClassUsingFactory {

  private final String parameter;

  @Factory(dataProvider = "dp")
  public SampleTestClassUsingFactory(String parameter) {
    this.parameter = parameter;
  }

  @BeforeMethod
  public void beforeMethod() {
    //Include your code to fire your Rest Call here
  }

  @Test
  public void testMethod() {
    System.err.println("Using the parameter " + parameter);
  }

  @DataProvider(name = "dp")
  public static Object[][] getTestData() {
    return new Object[][]{
        {"a"},
        {"b"},
        {"c"}
    };
  }
}

方法 2:使用数据提供者驱动的测试方法

在这种情况下,您的@Test方法由数据提供者提供支持,并在您的内部@BeforeMethod拦截传递给该@Test方法的参数并在其中进行其余调用初始化。

这是一个示例,它显示了实际情况

public class SampleTestClassUsingDataProvider {

  @BeforeMethod
  public void beforeMethod(ITestResult testResult) {
    Object[] parameters = testResult.getParameters();
    //Simulate as if we are doing something with the parameters array
    System.err.println("Parameters for the test method = " + Arrays.toString(parameters));
  }

  @Test(dataProvider = "dp")
  public void testMethod(String parameter) {
    System.err.println("Using the parameter " + parameter);
  }


  @DataProvider(name = "dp")
  public static Object[][] getTestData() {
    return new Object[][]{
        {"a"},
        {"b"},
        {"c"}
    };
  }

}

另外我希望测试方法根据传递的参数打印测试名称。

您可以让您的测试类实现该org.testng.ITest接口并让它返回一个自定义名称,但这一切都归结为您正在使用的实际报告器以及它是否尊重这一点。如果您只是实现自己的,它会很容易,org.testng.IReporter您可以根据需要进行此自定义


推荐阅读