Spock验证模拟与模拟交互一起引发的异常

罗文

我遇到的问题是,当我尝试在then块中验证是否已引发异常,并且已对模拟进行了调用时。

查看以下设置:

class B {
    def b(A a) {
        a.a()
    }
}

class A {
    def a() {
    }
}

def "foo"() {
    given:
    def a = Mock(A)
    a.a() >> { throw new RuntimeException() }
    B b = new B()

    when:
    b.b(a)

    then:
    thrown(RuntimeException)
    1 * a.a()
}

上面的测试失败,并显示消息:Expected exception java.lang.RuntimeException, but no exception was thrown,但是设置模拟的代码显式抛出了异常。

有趣的是,如果删除最后一行:1 * a.a()测试通过。在then块中合并另一个不验证异常的断言时,我没有类似的问题。

有什么想法吗?

蛋白石

应该通过以下方式配置和验证它:

@Grab('org.spockframework:spock-core:0.7-groovy-2.0')
@Grab('cglib:cglib-nodep:3.1')

import spock.lang.*

class Test extends Specification {
    def "foo"() {
        given:
        def a = Mock(A)
        B b = new B()

        when:
        b.b(a)

        then:
        thrown(RuntimeException)
        1 * a.a() >> { throw new RuntimeException() }
    }
}


class B {
    def b(A a) {
        a.a()
    }
}

class A {
    def a() {
    }
}

如果同时模拟和验证交互,则应在where/then块中配置模拟行为

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章