使用Spock对Groovy2.0进行单元测试:setup()
发布时间:2020-12-14 16:34:11 所属栏目:大数据 来源:网络整理
导读:我正在使用Spock为groovy-2.0编写单元测试,并使用gradle运行.如果我按照测试通过写. import spock.lang.Specificationclass MyTest extends Specification { def "test if myMethod returns true"() { expect: Result == true; where: Result = new DSLValid
我正在使用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:无法在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中,存储在实例字段中的对象不在要素方法之间共享.相反,每个要素方法都有自己的对象.
如果需要在要素方法之间共享对象,请声明@Shared字段. class MyTest extends Specification { @Shared obj = new DSLValidator() def "test if myMethod returns true"() { expect: Result == true where: Result = obj.myMethod() } } class MyTest extends Specification { @Shared obj def setupSpec() { obj = new DSLValidator() } def "test if myMethod returns true"() { expect: Result == true where: Result = obj.myMethod() } } 设置环境有两种固定方法: def setup() {} // run before every feature method def setupSpec() {} // run before the first feature method 我不明白为什么setupSpec()的第二个例子工作并且使用setup()失败,因为在documentation中说不然:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |