【问题标题】:Java common method/function for duplicate code重复代码的Java常用方法/函数
【发布时间】: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。

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

【问题讨论】:

  • 这是个好主意。你试过什么?
  • 我分别为失败和跳过的测试创建了两个单独的函数,但是我需要一个通用函数。还有'map.put(map.get(key_result), Status.AUTOSKIP.getValue());'并且 ...AUTOFAIL 需要有一些共同点,这不允许我将其作为一个单独的函数。

标签: java testing automated-tests testng listener


【解决方案1】:

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

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) 调用它

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    • 2015-05-17
    • 2021-07-07
    • 2020-01-07
    • 2014-02-17
    相关资源
    最近更新 更多