【发布时间】:2016-05-11 16:46:06
【问题描述】:
我的 Java TestNg 侦听器方法 onFinish() 中有一个重复的代码,我想将它分离到一个函数中,这样我就可以调用它两次。下面是我的方法:
@Override
public void onFinish(ITestContext testContext) {
HashMap<Object, Object> map = new HashMap<Object,Object>();
Object key_id = new Object();
map.put(key_id, "id");
Object key_result = new Object();
map.put(key_result, "result");
//Check for all the FAILED tests
for (ITestResult failedTest : testContext.getFailedTests().getAllResults()) {
Method method = failedTest.getMethod().getConstructorOrMethod().getMethod();
TestInfo annotation = method.getAnnotation(TestInfo.class);
try {
if(annotation!=null) {
for(String test_id: annotation.id()) {
map.put(map.get(key_result), Status.AUTOFAIL.getValue());
Integration.addTestResult(map);
}
} catch (SecurityException | IOException
| TestRailApiException | NullPointerException e) {
TestLogger.logError("Failed to find the annotation");
}
}
//Check for all the SKIPPED tests
for (ITestResult skippedTest : testContext.getSkippedTests().getAllResults()) {
Method method = skippedTest.getMethod().getConstructorOrMethod().getMethod();
TestInfo annotation = method.getAnnotation(TestInfo.class);
try {
if(annotation!=null) {
for(String test_id: annotation.id()) {
map.put(map.get(key_result), Status.AUTOSKIP.getValue());
Integration.addTestResult(map);
}
} catch (SecurityException | IOException
| TestRailApiException | NullPointerException e) {
TestLogger.logError("Failed to find the annotation");
}
}
从上面的方法可以看出,两个for循环的唯一区别是我先检查失败的测试,然后在另一个循环中跳过测试。内部区别是我首先将 AUTOFAIL 作为测试状态推送,然后对所有跳过的测试推送 AUTOSKIP。
作为一种好的做法,我想将其分离到常用函数中,然后调用该函数发送AUTOFAIL 和AUTOSKIP。
【问题讨论】:
-
这是个好主意。你试过什么?
-
我分别为失败和跳过的测试创建了两个单独的函数,但是我需要一个通用函数。还有'map.put(map.get(key_result), Status.
AUTOSKIP.getValue());'并且 ...AUTOFAIL需要有一些共同点,这不允许我将其作为一个单独的函数。
标签: java testing automated-tests testng listener