Spock框架只允许一个例外条件,然后'块

时间:2015-05-19 04:52:19

标签: groovy spock

org.spockframework:spock-core:1.0-groovy-2.4
Gradle 2.4
Groovy 2.3.10

我正在使用gradle和spock框架来测试我的java代码。但是,我正在测试的函数可以抛出我需要测试的3个不同的异常。但是,在我的then子句中,我列出了3个异常,如果没有抛出任何异常,则测试将通过。但是,我不断收到以下编译错误:

318: Only one exception condition is allowed per 'then' block @ line 318, column 9.
           notThrown NoResponseException

319: Only one exception condition is allowed per 'then' block @ line 319, column 9.
           notThrown NotConnectedException

我用于测试的spock函数。正在测试的函数可以抛出这些异常。

   def 'Create instant pubsub node'() {
       setup:
        smackClient.initializeConnection(domain, serviceName, resource, port, timeout, debugMode)
        smackClient.connectAndLogin(username, password)

        when:
        smackClient.getSPubSubInstance(smackClient.getClientConnection()).createInstantnode()

        then:
        notThrown XMPPErrorException
        notThrown NoResponseException
        notThrown NotConnectedException
    }

有没有办法在单个then子句中测试3个以上的异常?

我也试过这个并不是通过分成3个个人然后的条款来工作。

then:
notThrown XMPPErrorException

then:
notThrown NoResponseException

then:
notThrown NotConnectedException

2 个答案:

答案 0 :(得分:2)

我提出的最好的是使用where:条款

def 'Create instant pubsub node'() {
   setup:
    smackClient.initializeConnection(domain, serviceName, resource, port, timeout, debugMode)
    smackClient.connectAndLogin(username, password)

    when:
    smackClient.getSPubSubInstance(smackClient.getClientConnection()).createInstantnode()

    then:
    notThrown exception

    where:
    exception << [XMPPErrorException, NoResponseException, NotConnectedException]
}

我在simpler example

上创建了spock web console

答案 1 :(得分:1)

不幸的是,在单个(甚至多个 - 链接时) - notThrown块中检查多个then语句是不可能的。正如@BillJames所评论的那样,你可以使用noExceptionThrown或解决方案(只是好奇心 - 我不觉得它有用也不可读)我准备好了:

@Grab('org.spockframework:spock-core:1.0-groovy-2.4')
@Grab('cglib:cglib-nodep:3.1')

import spock.lang.*

class Test extends Specification {
    def sc = new SomeClass()

    def 'spec 1'() {
        when:
        sc.someMethod()

        then:
        noExceptionThrown()
    }

    def 'spec 2'() {
        when:
        sc.someMethod()

        then:
        notThrown(e)

        where:
        e << [E1, E2, E3]
    }
}

class SomeClass {
    def someMethod() {
    }
}

class E1 extends RuntimeException {}
class E2 extends RuntimeException {}
class E3 extends RuntimeException {}
相关问题