我遇到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)
答案 0 :(得分:0)
以下示例完美无缺:
@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) {}
}
也许你错误配置了什么?