Spock框架:间谍问题
我在Spock中使用Spy有一个问题,它要么不能正常工作,要么我的理解是错误的,所以我试图弄清楚这一点。 考虑这段代码(Java):
public class CallingClass { public String functionOne() { //does stuff return "one"; } public String functionTwo() { String one = functionOne(); return "some string " + one; } }
现在我想测试一下这个事实,即functionTwo
调用functionOne
以及定义functionOne
的返回值(想象一下,如果functionOne
真的很复杂,我不想在我的测试中执行它只是想将它存根并将其设置为返回一定的值)。 为此,我在Groovy中编写以下测试(使用Spock):
class CallingClassTest extends Specification { def "check that functionTwo calls functionOne"() { def c = Spy(CallingClass) c.functionOne() >> "mocked function return" when: def s = c.functionTwo() then: 1 * c.functionOne() s == "some string mocked function return" } }
为了做这样的事情,Spock要我拥有cglib
库,所以我的构建文件(在Gradle中)看起来像这样:
apply plugin: 'groovy' repositories { mavenCentral() } dependencies { compile 'org.codehaus.groovy:groovy:latest.release' testCompile 'org.spockframework:spock-core:latest.release' testCompile 'junit:junit:latest.release' testCompile 'cglib:cglib-nodep:latest.release' }
现在,当我运行测试时,我希望根本不会调用functionOne
,而是使用我的存根版本。 相反,我明白了:
Condition not satisfied: s == "some string mocked function return" | | | false | 19 differences (44% similarity) | some string (-)o(-------)n(-------)e(----) | some string (m)o(cked fu)n(ction r)e(turn) some string one Condition not satisfied: s == "some string mocked function return" | | | false | 19 differences (44% similarity) | some string (-)o(-------)n(-------)e(----) | some string (m)o(cked fu)n(ction r)e(turn) some string one at CallingClassTest.check that functionTwo calls functionOne(CallingClassTest.groovy:17)
更重要的是,如果我调试这个并在functionOne
设置一个断点,它会被调用:(
我错过了什么? 我的测试不应该使用stubbed functionOne
提供的,只返回字符串"mocked function return"
?
它应该是:
@Grab('org.spockframework:spock-core:0.7-groovy-2.0') @Grab('cglib:cglib-nodep:3.1') import spock.lang.* class CallingClassTest extends Specification { def "check that functionTwo calls functionOne"() { def c = Spy(CallingClass) when: def s = c.functionTwo() then: 1 * c.functionOne() >> "mocked function return" s == "some string mocked function return" } } public class CallingClass { public String functionOne() { "one" } public String functionTwo() { String one = functionOne() "some string $one" } }
当您同时进行间谍/模拟并validation时,应该如何指定返回值。