2017-10-29 96 views

回答

1

您將需要基本上利用一個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 
=============================================== 
+0

謝謝你! @KrishnanMahadevan先生!你當然成了我的導師:) –

+0

如果能幫助你,你能接受我的答案嗎? –

相關問題