2016-08-05 80 views
0

我想用KnownFault注释我的一些测试用例 - 这几乎可以做什么expectedException加上一些使用YouTrack的REST API的魔法。我还想有一个IntermittentFailure属性,这意味着我意识到测试可能偶尔会失败[异常] [消息],但我不希望这会阻止我的构建链的其余部分。testng - 创建KnownFault和IntermittentFailure注释

经过一番研究,我发现,我的测试类应该实现IHookable,然后我可以有这样的事情:

@Override 
public void run(IHookCallBack callBack, ITestResult result) { 
    callBack.runTestMethod(result); 
    if (result.getThrowable().getCause() instanceof IllegalArgumentException){ 
     System.out.println("This is expected."); 
     result.setThrowable(null); 
    } 
    else{ 
     System.out.println("Unexpected exception"); 
    } 
} 

的问题,这是实际执行invokeHookable的:

final Throwable[] error = new Throwable[1]; 

IHookCallBack callback = new IHookCallBack() { 
    @Override 
    public void runTestMethod(ITestResult tr) { 
    try { 
     invokeMethod(thisMethod, testInstance, parameters); 
    } catch (Throwable t) { 
     error[0] = t; 
     tr.setThrowable(t); // make Throwable available to IHookable 
    } 
    } 

    @Override 
    public Object[] getParameters() { 
    return parameters; 
    } 
}; 
hookable.run(callback, testResult); 
if (error[0] != null) { 
    throw error[0]; 
} 

不幸的是,最后一行意味着无论error阵列在run方法中完全不在我的手中,我的测试案例将会抛出异常。

那么,截取异常并以我想要的方式处理异常的正确方法是什么?

回答

1

你想要做的事情真的很有趣。你应该尝试建议更改https://github.com/cbeust/testng/pull/

但也许IHookable不是你可以使用的最佳听众。你试过IInvokedMethodListener

void afterInvocation(IInvokedMethod method, ITestResult result) { 
    if (result.getThrowable().getCause() instanceof IllegalArgumentException) { 
     System.out.println("This is expected."); 
     result.setThrowable(null); 
     result.setStatus(SUCCESS); // If you want to change the status 
    } else { 
     System.out.println("Unexpected exception"); 
    } 
} 
+0

很酷,工作。因此,在使用Listener的情况下,必须稍微修改基类:我添加了一个名为'TestListener'的类来完成您提出的实现,然后我必须使用@Listeners(TestListener.class)注释测试的基类' 。像魅力一样工作! – RekaB

+0

或者您可以使用任何其他侦听器检测机制,如果您更喜欢http://testng.org/doc/documentation-main.html#testng-listeners – juherr