【问题标题】:Re-utilize try-catch with closure and multiple params重新利用带有闭包和多个参数的 try-catch
【发布时间】:2018-03-21 13:16:23
【问题描述】:

努力实现以下目标:

  1. 由于经常使用相同的 try-catch 块,因此将其抽象为闭包
  2. 同时传递日志信息:类和方法名称

到目前为止,我有以下内容,但无法使其正常工作,我们将不胜感激一些提示.. 不是 groovy 专家

@Test
void eventListingJsonResponse() {


    assertionErrorClosure {

        EventListingTest.class, "eventListingJsonResponse" ->

        given()
            .header("accessTokenKey",accessTokenKey)
            .header("accessTokenSecret", accessTokenSecret)
        .expect()
                .statusCode(200)
            .and()
                .body("events.any {it.containsKey('clientid')}", is(true))
        .when()
            .get(basePath)
    }
}

def assertionErrorClosure(Closure closure) {

    def claz = 'c'
    def meth = 'm'

    logInfo(this.getClass(), "-- Start testing of $meth with clientId: $clientId --\n")

    try {
        closure()
    } catch (AssertionError e) {
        logWarning(claz, "Error testing $meth: \n\n$e")
    }
}

这可能吗?

提前致谢

【问题讨论】:

    标签: groovy


    【解决方案1】:

    你快到了,你必须像这样将闭包参数和闭包本身分别传递给assertionErrorClosure函数:

    assertionErrorClosure(this.class, "eventListingJsonResponse") {
    
        clazz, methodName ->
    
        print "hello world from class: ${clazz} and method: ${methodName}"
    
        //your test code here
    
    }
    
    def assertionErrorClosure(Class clazz, String methodName, Closure closure) {
    
        print("" + clazz + "-- Start testing of $methodName --\n")
    
        try {
            closure(clazz, methodName)
        } catch (AssertionError e) {
            logWarning(claz, "Error testing $methodName: \n\n$e")
        }
    }
    

    您可以将print() 替换为您的记录器,将this.class 替换为EventListingTest.class

    【讨论】:

      猜你喜欢
      • 2014-12-12
      • 1970-01-01
      • 2020-04-02
      • 1970-01-01
      • 2015-02-21
      • 2021-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多