java version 1.7.0_75
Gradle 2.2
Groovy: 2.3.6
spock-core.1.0
你好,
我有一个 java 函数,我正在尝试使用 spock 框架进行单元测试。如果有
NullPointerException
,该函数将抛出异常。 . public void disconnect() throws NullPointerException {
if(mClientConnection == null) {
throw new NullPointerException("mClientConnection has an invalid reference");
}
if(mClientConnection.isConnected()) {
mClientConnection.disconnect();
}
mClientConnection = null;
}
我正在尝试在我的 spock 单元测试中测试该条件。下面我试图捕捉是否抛出 NullPointerException。但是,这是不正确的,因为我收到以下错误:
'expect' is not allowed here; instead, use one of: [and, then] @ thrown() != nullPointerException
这是我的单元测试 spock 测试:
def 'Disconnect from a connected client'() {
setup:
SmackClient smackClient = SmackClient.getSmackClient()
when: /* Disconnect from a existing connection */
smackClient.disconnect()
expect:
thrown() != nullPointerException
}
非常感谢您的任何建议,
最佳答案
遵循的正确词when
是 then
(如错误消息所述)。
还有它的thrown(NullPointerException)
.
请参阅文档:
Exception conditions are used to describe that a when block should throw an exception. They are defined using the thrown() method, passing along the expected exception type. For example, to describe that popping from an empty stack should throw an EmptyStackException, you could write the following:
when: stack.pop() then: thrown(EmptyStackException) stack.empty
关于unit-testing - 测试 java 函数中抛出的异常,以便在 spock 单元测试中捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29763699/