我正在使用 Spock 为 groovy-2.0 编写单元测试,并使用 gradle 运行。如果我在测试通过之后写。
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。
但是,如果我编写 setup() 函数并在 setup() 中创建对象,我的测试将失败:Gradel 说:FAILED: java.lang.NullPointerException: Cannot invoke method myMethod() on null object
以下是 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()
}
}