Java 如何从Spock规范类中提取BDD元语句
假设我们有一个如下所示的Spock规范类Java 如何从Spock规范类中提取BDD元语句,java,groovy,bdd,spock,Java,Groovy,Bdd,Spock,假设我们有一个如下所示的Spock规范类 class SomeFeature extends Specification { def "some scenario"() { given: "some resource" def resource = someResource() when: "some action is taken" someAction() then: "some condition
class SomeFeature extends Specification {
def "some scenario"() {
given: "some resource"
def resource = someResource()
when: "some action is taken"
someAction()
then: "some condition must be met"
true == someCondition()
}
}
如何提取BDD元语句,如某些场景
,给定
,何时
,然后
?处理源文件很简单,但我想知道是否可以使用反射来实现这一点
顺便说一句,获取这些信息的动机是为了促进产品所有者和开发人员之间的沟通,这样产品所有者就可以知道实现和验证了哪些行为,而无需查看源代码
非常感谢。在冷冰冰的日子里,这有一些问题
我不认为反思会有帮助,因为它不会让你了解方法的内容 您可以通过从源代码生成AST,然后遍历它以查找感兴趣的节点来实现 给定字符串中的代码,如下所示:
def code = '''import spock.*
class SomeFeature extends Specification {
def "some scenario"() {
given: "some resource"
def resource = someResource()
when: "some action is taken"
someAction()
then: "some condition must be met"
true == someCondition()
}
def "another"() {
given: 'a value 1'
def value = 1
then: '1 == 1'
value == 1
}
}'''
您可以生成一个AST:
import org.codehaus.groovy.antlr.*
import org.codehaus.groovy.antlr.parser.*
def ast = new GroovyRecognizer(
new GroovyLexer(
new StringReader( code ) ).plumb() ).with { p ->
p.compilationUnit()
p.AST
}
然后你可以做这样的事情(这可能不是最干净的方式,因为我受时间限制);-)
这给了我输出:
Specification 'SomeFeature'
Scenario 'some scenario'
GIVEN 'some resource'
WHEN 'some action is taken'
THEN 'some condition must be met'
Scenario 'another'
GIVEN 'a value 1'
THEN '1 == 1'
希望它能帮助…请参阅。块描述可用于扩展。Spock 1.0将支持BDD风格的报告。@PeterNiederwieser Lol这比我的树黑客攻击要好得多:-D@PeterNiederwieser非常感谢。我只是在玩报告扩展。这绝对证明了斯波克有能力做我所期待的事情。我很高兴看到这个特性成为稳定版本的一部分。顺便说一句,我们正在评估一些BDD框架,包括Spock和Cucumber,然后再选择一个作为我们公司的标准。这一报道功能肯定会使斯波克在与Cucumber的竞争中处于更有利的地位。
Specification 'SomeFeature'
Scenario 'some scenario'
GIVEN 'some resource'
WHEN 'some action is taken'
THEN 'some condition must be met'
Scenario 'another'
GIVEN 'a value 1'
THEN '1 == 1'