0
我想基于业务逻辑多次运行我的测试方法。有没有办法改变InvocationCount来实现相同?任何其他建议也是受欢迎的。如何在运行时在TestNG中设置InvocationCount - @Test?
我想基于业务逻辑多次运行我的测试方法。有没有办法改变InvocationCount来实现相同?任何其他建议也是受欢迎的。如何在运行时在TestNG中设置InvocationCount - @Test?
您将需要基本上利用一个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 ([email protected])
...
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
===============================================
谢谢你! @KrishnanMahadevan先生!你当然成了我的导师:) –
如果能帮助你,你能接受我的答案吗? –