测试在 spock 单元测试中捕获的 java 函数中抛出的异常

Testing for a exception that is thrown in a java function to be captured in a spock unit test

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

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