我为我的注释创建了一个 java 接口(interface)。我现在正在编写一个 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
。
关于Groovy 获取当前方法注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15794940/