Java common method/function 重复代码

Java common method/function for duplicate code

我的 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。

作为一个好的做法,我想将其分离到公共函数中,然后调用该函数来发送 AUTOFAILAUTOSKIP

将循环提取到一个单独的方法中,并使用您要循环的内容对其进行参数化:

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)

当然,这并不是您可以在此处进行的所有改进,但我相信这解决了您最初的问题。