如何在TestNG-@Test中的运行时设置InvocationCount



我想基于业务逻辑多次运行我的测试方法。有没有一种方法可以改变InvocationCount来实现同样的目的?任何其他建议也欢迎。

您基本上需要利用IAnnotationTransformer来实现这一点。

下面是一个示例,展示了这一点。

标记注释,我们将使用它来指示特定的测试方法需要多次运行。

import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
/**
* A Marker annotation which is used to express the intent that a particular test method
* can be executed more than one times. The number of times that a test method should be
* iterated is governed by the JVM argument : <code>-Diteration.count</code>. The default value
* is <code>3</code>
*/
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target({METHOD})
public @interface CanRunMultipleTimes {
}

测试类如下所示。

import org.testng.annotations.Test;
import java.util.concurrent.atomic.AtomicInteger;
public class TestClassSample {
private volatile AtomicInteger counter = new AtomicInteger(1);
@CanRunMultipleTimes
@Test
public void testMethod() {
System.err.println("Running iteration [" + counter.getAndIncrement() + "]");
}
}

以下是注释转换器的外观。

import org.testng.IAnnotationTransformer;
import org.testng.annotations.ITestAnnotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
public class SimpleAnnotationTransformer implements IAnnotationTransformer {
@Override
public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {
if (testMethod == null || testMethod.getAnnotation(CanRunMultipleTimes.class) == null) {
return;
}
int counter = Integer.parseInt(System.getProperty("iteration.count", "3"));
annotation.setInvocationCount(counter);
}
}

套件xml文件如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="46998341_Suite" verbose="2">
<listeners>
<listener class-name="com.rationaleemotions.stackoverflow.qn46998341.SimpleAnnotationTransformer"/>
</listeners>
<test name="46998341_Test">
<classes>
<class name="com.rationaleemotions.stackoverflow.qn46998341.TestClassSample"/>
</classes>
</test>
</suite>

以下是输出的样子:

... TestNG 6.12 by Cédric Beust (cedric@beust.com)
...
Running iteration [1]
Running iteration [2]
Running iteration [3]
PASSED: testMethod
PASSED: testMethod
PASSED: testMethod
===============================================
46998341_Test
Tests run: 3, Failures: 0, Skips: 0
===============================================
===============================================
46998341_Suite
Total tests run: 3, Failures: 0, Skips: 0
===============================================

你能在类级别中做到这一点吗。感谢您的帮助,方法级别工作得很完美,只是想知道我们是否可以为类级别也做

我在下面试了一下,但没用。使用类型

@Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target({METHOD, TYPE}) public @interface CanRunMultipleTimes { }

最新更新