Spock框架:如何捕获被测方法的返回值?
在Spock中用Spy验证方法返回值的正确姿势
嘿,别担心,Spock完全支持你想要实现的需求——通过Spy对象确认被测代码(CUT)中某方法的返回结果是否符合预期。你遇到的报错大概率是写法不符合Spock语法导致的,咱们来拆解问题并给出解决方案:
先分析你遇到的报错
你看到的No signature of method: core.ConsoleHandler.compileOutputLines() is applicable for argument types: (org.spockframework.lang.Wildcard) values: [[*_]]错误,核心原因是你调用compileOutputLines()时传入了它不接受的参数(这里的[*_]是Spock的集合展开语法,但显然这个方法不需要参数,或者参数类型不匹配)。
Spock Spy验证返回值的两种常见场景
Spy的核心作用是包装真实对象,既可以保留真实方法逻辑,也能灵活存根或验证交互。针对你的需求,分两种场景给出正确写法:
场景1:验证真实方法的返回结果
如果你希望让compileOutputLines()执行真实逻辑,然后验证它的返回值是否符合预期,直接调用方法后断言即可:
def "verify compileOutputLines returns expected result from real implementation"() { given: // 创建Spy对象,包装真实的ConsoleHandler实例 def consoleHandler = Spy(core.ConsoleHandler) when: // 直接调用目标方法,获取返回结果 def outputLines = consoleHandler.compileOutputLines() then: // 断言返回值与预期一致 outputLines == ["expected line 1", "expected line 2"] }
场景2:存根方法返回值+验证交互
如果你需要让compileOutputLines()返回指定值(而不是执行真实逻辑),同时验证它是否被正确调用,写法如下:
def "stub compileOutputLines and verify it's called correctly"() { given: // 创建Spy时,存根compileOutputLines方法的返回值 def consoleHandler = Spy(core.ConsoleHandler) { compileOutputLines() >> ["stubbed output line 1", "stubbed output line 2"] } when: // 调用CUT中依赖compileOutputLines的业务方法 def processedResult = consoleHandler.processUserInput() then: // 断言业务方法的处理结果符合预期 processedResult == ["processed: stubbed output line 1"] // 验证compileOutputLines被调用了1次(如果需要验证调用次数) 1 * consoleHandler.compileOutputLines() // 也可以直接验证存根的返回值 consoleHandler.compileOutputLines() == ["stubbed output line 1", "stubbed output line 2"] }
额外注意:如果方法有参数
如果compileOutputLines是带参数的方法,你需要确保存根或验证时的参数匹配方法签名,比如:
// 假设方法签名是compileOutputLines(List<String> inputLines) def "handle method with parameters"() { given: def consoleHandler = Spy(core.ConsoleHandler) { // 匹配特定参数,返回指定值 compileOutputLines(["input line"]) >> ["output line"] // 或者匹配任意参数,返回指定值 compileOutputLines(_) >> ["default output"] } when: def result = consoleHandler.compileOutputLines(["input line"]) then: result == ["output line"] 1 * consoleHandler.compileOutputLines(["input line"]) }
总的来说,Spock完全具备你需要的验证机制,只要确保方法调用的签名匹配,就能避免类似的报错啦。
内容的提问来源于stack exchange,提问作者mike rodent
相关产品推荐
相关产品推荐

