Groovy获取当前方法注释

时间:2013-04-03 18:17:46

标签: groovy geb

我为我的注释创建了一个java接口。我现在正在编写一个geb spock测试,我想打印注释值,以便它显示在gradle报告中。这可能吗?这是我的测试用例,如果我做错了,请告诉我

class Checkout extends GebReportingSpec {

    @TestCase(someID="12345")
    def "A checkout 3-D script"() {
        // My test steps.....
    }
}

2 个答案:

答案 0 :(得分:2)

使用StackTraceUtils.sanitize获取当前方法并使用反射来迭代注释:

import java.lang.annotation.*

import org.codehaus.groovy.runtime.StackTraceUtils

class Checkout {
  @TestCase(someID="12345")
  def "yeah a"() {
    printTestCaseId()
    // My test steps.....
  }

  def printTestCaseId() {
    def stack = StackTraceUtils.sanitize(new Throwable()).stackTrace[1]
    def method = getClass().declaredMethods.find { it.name == stack.methodName }
    println method
    def someID = method.annotations[0].someID()
    println someID
    assert someID == "12345"
  }

}

@Retention (RetentionPolicy.RUNTIME)
@interface TestCase { String someID() }

co = new Checkout()
co."${'yeah a'}"()

如果您是遍历方法的人,则不需要StackTraceUtils

答案 1 :(得分:0)

spockframework(版本" spock-core-1.1-groovy-2.4")提供了访问注释的方法:

package com.test.integration.spec

import com.test.integration.annotation.Scenario
import com.test.integration.annotation.TestCase

import spock.lang.Specification

@Scenario("AnnotationSpec")
class AnnotationSpec extends Specification {

    String scenario
    String test_case

    def setup() {
        scenario = specificationContext.currentSpec.getAnnotation(Scenario).value()
        test_case = specificationContext.currentFeature.featureMethod.getAnnotation(TestCase).value()
    }

    @TestCase("case-001")
    def 'spock provides way of accessing annotation'(){

        expect:
        "AnnotationSpec" == scenario
        "case-001" == test_case
    }

}