我正在使用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()
}
}
Run Code Online (Sandbox Code Playgroud)
myMethod()是DSLValidator类中的一个简单方法,它只返回true.
但是如果我编写一个setup()函数并在setup()中创建对象,我的测试就会失败:Gradel说:FAILED: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()
}
}
Run Code Online (Sandbox Code Playgroud)
有人可以帮忙吗?
这是我遇到问题的解决方案:
import spock.lang.Specification
class DSLValidatorTest extends Specification {
def validator
def setup() {
validator = new DSLValidator() …Run Code Online (Sandbox Code Playgroud)