2016-08-23 67 views
0

我想設置特定測試用例的調用計數。以下代碼是爲偵聽器編寫的。目標是循環一個特定的測試方法給定的次數。聽衆工作正常,但setInvocationCount未按預期工作。如何使用TestNG監聽器設置測試方法的調用計數?

Listener類: -

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()); 
    } 

TestNG的XML: -

<?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> 

測試案例: -

@Test 
public void TC_01_LoginToSSOApplicationViaInstructor() {  
    System.out.println("1"); 
} 

@Test 
public void TC_02_InstructorCreatesCourse() {  
    System.out.println("2"); 

} 

@Test 
public void TC_03_LoginToSSApplicationViaStudent() { 
    System.out.println("3"); 
} 

@Test 
public void TC_04_EnrollStudentInCourse() { 

} 

回答

2

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); 
    } 
    } 
} 
+0

你能提供更深入爲什麼這是一個更好的傾聽者? – CARE

+0

由於IAnnotationTransformer在運行測試(init階段)之前由TestNG使用,並且在運行期間使用IInvokedMethodListener。在運行階段更改值可能會或可能無法工作。 – juherr

+0

謝謝,朱利安赫爾。 –

相關問題