首页 > 解决方案 > 尝试使用断言运行 AfterMethod

问题描述

我的测试课上有很多测试方法。我的目标是能够使用两次断言:第一次在每个测试中,第二次在每个 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");
   }
}

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

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

标签: javaseleniumtestng

解决方案


在这种情况下,您应该使用 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中的代码。


推荐阅读