unit-testing - 测试 java 函数中抛出的异常,以便在 spock 单元测试中捕获

标签 unit-testing groovy gradle spock

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
}

非常感谢您的任何建议,

最佳答案

遵循的正确词whenthen (如错误消息所述)。

还有它的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

关于unit-testing - 测试 java 函数中抛出的异常,以便在 spock 单元测试中捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29763699/

相关文章:

grails - Netbeans Groovy 1.8支持

grails - 有状态与无状态服务 Grails

当 keystore 或属性不存在时,Android 签名应用回退

java - 似乎无法使JavaFX与Java 10 JDK和Gradle一起使用

android - 如何在android模块上运行单元测试?

java - Jmock/junit 测试

c# - NUnit 测试错误?预期为 <MyType> 但为 <MyType>

c# - 使用 MsBuild 命令行执行单元测试

grails - 常规闭包继承

unit-testing - gcov 用于大型项目(静态库,...)