如何使用TestNG侦听器设置测试方法的调用计数?

时间:2016-08-23 12:52:10

标签: java automation automated-tests testng listeners

我正在尝试为特定的测试用例设置调用计数。以下代码是为侦听器编写的。目标是将特定测试方法循环给定次数。监听器工作正常,但 setInvocationCount 未按预期工作。

听众类: -

for (UIViewController *vc in ((UINavigationController *)[[self window] rootViewController]).viewControllers) {
            if ([vc isKindOfClass:[ViewController class]]) {
                ViewController *viewController = (ViewController *)vc;
                [viewController setOAuthToken:token oauthVerifier:verifier];
            }
        }

testNG xml: -

public class InvokedListener implements IInvokedMethodListener {

    String count = System.getProperty("count", "100");
    int counter = Integer.parseInt(count);
    int count1;

    @Override
    public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {

        System.out.println("before invocation of " + method.getTestMethod().getMethodName());
        String methodName = method.getTestMethod().getMethodName();

        if (methodName.contains("TC_02_InstructorCreatesCourse")) {
            System.out.println("The listener is activated for:-" + method.getTestMethod().getMethodName());
            method.getTestMethod().setInvocationCount(20);
            System.out.println("Invocation count is set to :-" + counter);
        }
    }

    @Override
    public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
        System.out.println("after invocation " + method.getTestMethod().getMethodName());
    }

     

<?xml version="1.0" encoding="UTF-8"?>

测试案例: -

        <listener class-name="InvokedLister" />

    </listeners>

<test name="CourseCreation"
    preserve-order="true"  enabled="true">
    <classes>
        <class
            name="TestCases" />
    </classes>
</test>

1 个答案:

答案 0 :(得分:3)

为了您的目的,

IAnnotationTransformer or IAnnotationTransformer2是更好的倾听者选择:

public class MyTransformer implements IAnnotationTransformer {

  private final int counter;

  public MyTransformer() {
    String count = System.getProperty("count", "100");
    counter = Integer.parseInt(count);
  }

  public void transform(ITest annotation, Class<?> testClass,
      Constructor testConstructor, Method testMethod) {
    if (testMethod.getName().contains("TC_02_InstructorCreatesCourse")) {
      System.out.println("The listener is activated for:-" + testMethod.getName());
      annotation.setInvocationCount(20);
      System.out.println("Invocation count is set to :-" + counter);
    }
  }
}