【问题标题】:Spock exception interaction fails but mockito exception interaction works?Spock 异常交互失败但 mockito 异常交互有效?
【发布时间】:2016-01-06 18:35:51
【问题描述】:

我在 Spock 规范和异常处理方面遇到问题。

我有一些代码调用服务并捕获某种类型的异常。在 catch 块中抛出了另一种类型的异常:

try { 
   int result = service.invoke(x,y);
   ...
} catch (IOException e) {
   throw BusinessException(e);
}

以下测试用例使用 mockito 模拟工作:

given: "a service that fails"
def service = mock(Service)
when(service.invoke(any(),any())).thenThrow(new IOException())

and: "the class under test using that service"
def classUnderTest = createClassUnderTest(service)

when: "the class under test does something"
classUnderTest.doSomething()

then: "a business exception is thrown"
thrown(BusinessException)

所有测试均通过

但在使用 Spock 处理服务交互时,以下测试用例会失败:

given: "a service that fails"
def service = Mock(Service)
service.invoke(_,_) >> { throw new IOException() }

and: "the class under test using that service"
def classUnderTest = createClassUnderTest(service)

when: "the class under test does something"
classUnderTest.doSomething()

then: "a business exception is thrown"
thrown(BusinessException)

预期为 BusinessException' 类型的异常,但未引发异常

我不确定这里发生了什么。它适用于 mockito,但不适用于 Spock。

我没有验证引发异常的服务,因此不需要在 when/then 块中进行设置。

(使用 groovy-all:2.4.5, spock-core:1.0-groovy-2.4)

【问题讨论】:

    标签: unit-testing groovy spock


    【解决方案1】:

    以下示例运行良好:

    @Grab('org.spockframework:spock-core:1.0-groovy-2.4')
    @Grab('cglib:cglib-nodep:3.1')
    
    import spock.lang.*
    
    class Test extends Specification {
    
        def "simple test"() {
            given:
                def service = Mock(Service) {
                    invoke(_, _) >> { throw new IOException() }
                }
                def lol = new Lol()
                lol.service = service
    
             when:
                lol.lol()
            then:
                thrown(BusinessException)
        }
    }
    
    class Service {
        def invoke(a, b) {
            println "$a $b"
        }
    }
    
    class Lol {
        Service service 
    
        def lol() {
            try {
                service.invoke(1, 2)
            } catch(IOException e) {
                throw new BusinessException(e)
            }
        }
    }
    
    class BusinessException extends RuntimeException {
        BusinessException(Exception e) {}
    }
    

    也许你配置错误?

    【讨论】:

    • 这很奇怪......我恢复使用 Spock 交互并且代码现在可以工作了。小精灵。将删除问题。感谢您的回复。
    • 可能是类路径问题?我宁愿将它与我的答案一起保留原样 - 以供未来的提问者使用。这是一个完整的例子。
    猜你喜欢
    • 2014-11-05
    • 1970-01-01
    • 2015-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 2020-11-14
    相关资源
    最近更新 更多