我在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(使用groovy-all: 2.4.5 spock-core: 1.0 - 2.4)
下面的例子运行得很好:
@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) {}
}
也许你配置错了什么?