【问题标题】:Spock mocked method doesn't return correct valuesSpock 模拟方法没有返回正确的值
【发布时间】:2015-12-08 06:10:28
【问题描述】:

给定一个类 Foo

Foo {
    boolean bar() {}
}

为什么当我使用 Spock 来模拟 Foo 时

Foo fooInstance = Mock(Foo)
fooInstance.bar() >>> [true, true, true]

调用fooInstance.bar() 总是返回false?

不确定是否有区别,但测试是在 Groovy/Spock 中,而 Foo 是在 Java 8 中。

【问题讨论】:

  • 能否提供完整的规范?
  • 您的Foo 示例代码不是class,除非您忘记在此处添加。
  • 你为什么试图用你的布尔值模拟一个数组的返回值?我想这就是你想要的: class Foo{ boolean bar() { } } void "test foo"(){ Foo fooInstance = Mock(Foo) fooInstance.bar() >> true;期望: fooInstance.bar() }

标签: mocking spock


【解决方案1】:

按我的预期工作,这是代码(我必须修复你的 Foo 类,以便它可以通过抛出 RuntimeException 来编译 - 但在测试运行时你永远不会看到这个):

/* In Groovy 2.4 */
import spock.lang.Specification

class FooTests extends Specification {

    def "test that bar always returns true"(){
        given: "a mock Foo"
        def mockFoo = Mock(Foo)
        mockFoo.bar() >>> [true, true, true]

        when: "we call bar 3 times"
        def result1 = mockFoo.bar()
        def result2 = mockFoo.bar()
        def result3 = mockFoo.bar()

        then: "the result should always be true"
        result1 == true
        result2 == true
        result3 == true
    }
}

/* In Java 8: */
class Foo {
    boolean bar() {
        throw new RuntimeException("should not happen");
    }
}

将三个固定返回值中的任何一个更改为 false 并且测试失败。希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    • 2016-06-01
    • 2014-04-08
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    相关资源
    最近更新 更多