8
我正在使用Spock为groovy-2.0编写单元测试,并使用gradle来运行。如果我在测试通过后写下。使用Spock进行单元测试Groovy2.0:setup()
import spock.lang.Specification
class MyTest extends Specification {
def "test if myMethod returns true"() {
expect:
Result == true;
where:
Result = new DSLValidator().myMethod()
}
}
myMethod()是DSLValidator类中的一个简单方法,它只是返回true。
但是,如果我写的设置()函数创建设置()的对象,我的测试失败:格拉德尔说:失败:显示java.lang.NullPointerException:不能为null对象上调用方法myMethod的()
以下是它看起来像setup(),
import spock.lang.Specification
class MyTest extends Specification {
def obj
def setup(){
obj = new DSLValidator()
}
def "test if myMethod returns true"() {
expect:
Result == true;
where:
Result = obj.myMethod()
}
}
有人可以帮忙吗?
这里是我的问题的解决方案:
import spock.lang.Specification
class DSLValidatorTest extends Specification {
def validator
def setup() {
validator = new DSLValidator()
}
def "test if DSL is valid"() {
expect:
true == validator.isValid()
}
}
奇怪...... Spock文档可能会对此做出澄清......我不会说obj是在特征方法之间共享的,而是在每个fixture被调用之前设置的。 – 2012-01-31 21:18:06
你不明白的是什么?要素方法之间共享@Shared字段_is_,并且应该使用字段初始值设定项或'setupSpec'方法进行设置。 'setup'在这里不是一个好的选择,因为在'where'块被评估之后它会被调用。 – 2012-02-01 15:25:09
感谢您的澄清 – 2012-02-01 16:47:04