【发布时间】: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