尝试使用断言 运行 AfterMethod

Trying to run AfterMethod with assertion

我在测试中有很多测试方法class。我的目标是能够使用断言两次:第一次在每个测试中,第二次在每个 AfterMethod 测试中。

这是我的代码示例:

 @AfterMethod(alwaysRun = true )
public void reportTestFail() {

   String a = getAllParameters().get("A");
   if (a.contains("1")) {
       asserter.fail("1 is found in parameters");
   }
   else {
       asserter.assertTrue(true,"Test passed");
   }
}

为什么我总是在每次测试结束时得到失败的配置?

我不能在测试方法之外断言吗?

在这种情况下,您应该使用 TestNG IInvokedMethodListener2IInvokedMethodListener(对于 TestNG 版本 7+)并在 afterInvocation 中进行额外的验证。在这个方法的实现中,你应该在 try-catch 块和 catch 块中编写你的断言,你应该将 testMethod 状态设置为失败并设置异常。例如:

public void afterInvocation(IInvokedMethod method, ITestResult testResult, ITestContext context){
 try{
  //perform addition validations
 }catch(Exception e){
   //assertion failed
   //update testResult to fail
 }
}

要修改测试用例的结果,请参考 qaf 中的代码。