【问题标题】:Using runtime variables in spock verification在 spock 验证中使用运行时变量
【发布时间】:2020-07-02 23:28:10
【问题描述】:

我正在尝试编写一个简单的测试,我想用一些运行时变量来验证模拟调用。目前它看起来像这样:

class Spec extends Specification implements SampleData {

    EventBus eventBus = Mock()

    Facade facade = new Configuration().facade(eventBus)

    def "when the method is called an proper event is emitted"() {
        when:
            def id = facade.call(sampleData)

        then:
            1 * eventBus.push(_ as Event)
    }

}

但我想要实现的也是验证事件的有效负载是否正确 - 这意味着事件包含id,如下所示:

then:
        1 * eventBus.push(new Event(id))

有没有可能在 Spock 中实现这样的验证?

【问题讨论】:

    标签: java unit-testing testing spock


    【解决方案1】:

    您可以通过在EventBus 上存根push() 方法来捕获Event

    def "when the method is called a proper event is emitted"() {
        given:
            EventBus eventBus = Mock()
            Facade facade = new Configuration().facade(eventBus)
            Event received
        when:
            def id = facade.call(sampleData)
        then:
            1 * eventBus.push(_ as Event) >> { Event event -> received = event }
            received.id == id
    }
    

    【讨论】:

    • 这不是不必要的复杂吗?如果Event 有一个正确的equals 方法,它应该像OP 建议的那样工作,这不是必需的。
    • 不幸的是不是@kriegaex,因为交互被移动到when块之前,所以它将是...addInteraction(...addEqualArg(new Event(id)).build()); java.lang.Object id = facade.call(sampleData),因此不会编译。我能想出的唯一其他解决方案是影响通过模拟生成的 id,以便可以在 given 块中定义它。
    • 是的,当然。我不应该对一个问题或答案发表评论,我只是在查看我的新闻提要时粗略地看了一眼。这很尴尬。我又蠢又丑。我认为这个问题只是关于参数匹配。
    • @kriegaex,具有讽刺意味的是,当我意识到解决方案更复杂时,我在删除它之前对 OP 发表了关于 equals 的相同评论。
    • 感谢你们的 cmets,提供的答案对我有很大帮助:) - 我还是希望 Spock 提供更简单的东西:P
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 2015-12-29
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    相关资源
    最近更新 更多