Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spock-交互测试后测试失败_Spock - Fatal编程技术网

Spock-交互测试后测试失败

Spock-交互测试后测试失败,spock,Spock,此测试仅在测试条件时有效。当与交互测试混合时,它会失败 class Test extends Specification { class Inner { public String greet() { return "hello" } } def "simple test"() { given: def inner = Mock(Inner) inner.greet() >&g

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

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
应该是:

@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"
    }
}

让我们谈谈发生了什么事。(如果不想,请阅读“”部分。)

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

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

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

given:
    def inner = Mock(Inner)
    1 * inner.greet() >> message 
expect:
    "hi" = inner.greet()
where:
    message = "hi"
离别的想法。。。我希望您没有测试在测试中设置的值。这实际上是在断言1==1。如果您想在测试行为的同时测试实际代码,我建议您使用间谍

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

谢谢但这对我来说毫无意义。理想情况下,我们需要在检查测试结果之前设置模拟行为,所以您可以在方法的设置块中进行设置。这就是spock的工作原理。这就是我所做的,在“给定”块中设置此行为。我猜given和setup是一样的。不完全一样,请看这里:given是setup的别名。它们是完全一样的东西