我的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
。
答案 0 :(得分:2)
将循环提取到一个单独的方法中,并使用您循环的内容进行参数化:
void loop(Collection<ITestResult> results, Status status){
for(ITestResult result : results){
(... use status here ...)
}
}
并使用:loop(testContext.getFailedTests().getAllResults(), Status.AUTOFAIL)
和loop(testContext.getSkippedTests().getAllResults(), Status.AUTOSKIP)
当然,这不是你在这里可以做的所有改进,但是我相信这解决了你原来的问题。