重复代码的Java通用方法/函数

标签 java testing automated-tests testng listener

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

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

关于重复代码的Java通用方法/函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37168738/

相关文章:

java - 如何在没有 JDBC 4.2 驱动程序的情况下从 java.sql.Timestamp 获取 java.time 对象?

python - 异常引发不会反射(reflect)在测试用例中,即使在日志中看到异常引发

testing - 在 groovy 中测试的方法中模拟静态方法返回调用

javascript - 如何使用 CasperJS 提交列表中的项目

java - 从闰年计算年数

java - 什么是系统负载?

java - 大量的事件,如何缩小代码库?

testing - Jenkins 测试结果分析器不显示结果

c# - Selenium 测试在 IE11 中不起作用

webkit - 如何减少phantomjs内存消耗?