重新利用带有闭包和多个参数的try-catch

时间:2018-03-21 13:16:23

标签: groovy

尝试实现以下目标:

  1. 由于经常使用相同的try-catch块,因此将其抽象为Closure
  2. 也传递日志记录信息:类和方法名称
  3. 到目前为止我有以下内容但是无法让它工作,一些提示会非常感激..不是一个时髦的专家

    @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")
        }
    }
    

    这可能吗?

    提前致谢

1 个答案:

答案 0 :(得分: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