我为我的注释创建了一个 java 接口。我现在正在编写一个 geb spock 测试,我想打印注释值,以便它显示在 gradle 报告中。这可能吗?这是我的测试用例,如果我做错了,请告诉我
class Checkout extends GebReportingSpec {
@TestCase(someID="12345")
def "A checkout 3-D script"() {
// My test steps.....
}
}
使用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
人,则不需要。
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
}
}