【问题标题】:Spock - test fails after interaction testingSpock - 交互测试后测试失败
【发布时间】:2015-09-24 16:08:01
【问题描述】:

此测试仅在测试条件时才有效。当与交互测试混合时,它会失败。

class Test extends Specification {

   class Inner {
      public String greet() {
         return "hello"
      }
   }

   def "simple test"() {

      given:
         def inner = Mock(Inner)
         inner.greet() >> { "hi" }
      when:
         def msg = inner.greet()
      then:
         1 * inner.greet() // Below will pass when this line commented out.
         msg == "hi"
   }
}

删除交互测试后测试将通过。

Condition not satisfied:

msg == "hi"
|   |
|   false
null

【问题讨论】:

    标签: spock


    【解决方案1】:

    应该是:

    @Grab('org.spockframework:spock-core:0.7-groovy-2.0')
    @Grab('cglib:cglib-nodep:3.1')
    
    import spock.lang.*
    
    class Test extends Specification {
    
        class Inner {
            public String greet() {
                return "hello"
            }
        }
    
        def "simple test"() {
            given:
                def inner = Mock(Inner)
            when:
                def msg = inner.greet()
            then:
                1 * inner.greet() >> "hi"
                msg == "hi"
        }
    }
    

    【讨论】:

    • 谢谢。但这对我来说没有意义。理想情况下,我们需要在检查测试结果之前设置模拟行为。
    • 所以你可以做一个方法的设置块。这就是 spock 的工作原理。
    • 这正是我所做的,在“给定”块中设置了这种行为。我猜给定和设置是一样的。
    • 不完全是,请看这里:stackoverflow.com/questions/30875514/…
    • given 是 setup 的别名。它们是完全一样的
    【解决方案2】:

    让我们谈谈正在发生的事情。 (或者如果您不想,请阅读“Scope of Interactions”部分。)

    正在发生的事情是范围界定问题。您可能知道,您可以有多个顺序的 when/then 对;在 then 块中完成的任何 Mocking 实际上仅限于其 when 块。如果已在 when/then 范围之外定义了 Mocked 方法会发生什么? then 块中定义的 Mock 优先。

    恭喜!您偶然发现了 only 覆盖已建立的 Mocked 值/方法的方法。在新文档发布之前,我花了很长时间弄清楚它是如何工作的。

    所以我们知道您正在覆盖定义要返回的值的模拟。我们如何从这里开始?

    given:
        def inner = Mock(Inner)
        1 * inner.greet() >> message 
    expect:
        "hi" = inner.greet()
    where:
        message = "hi"
    

    分手的想法...我希望您没有测试您在测试中设置的值。这实际上是断言 1 == 1。如果你想在测试行为的同时测试你的实际代码,我建议使用 Spy

    given:
        def inner = Spy(Inner)
        1 * inner.greet() >> { 
            callRealMethod() // Actual method, read the documentation I linked
        }
    expect:
        "hi" = inner.greet()
    

    【讨论】:

      猜你喜欢
      • 2021-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-05
      • 2017-01-25
      • 2020-05-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多