1

所以我知道如何在我的处理程序单元测试中正确检查何时引发异常。

但是,当我想确保没有引发异常时,正确的方法是什么?

这是迄今为止我想出的最好的:

def "No exception is thrown"() {
    given:
    def noExceptionThrown = false

    when:
    def result =  RequestFixture.handle(new TestEndpoint(), { fixture -> fixture.uri("path/a)})

    then:
    try {
        result.exception(CustomException)
    } catch(ratpack.test.handling.HandlerExceptionNotThrownException e) {
        noExceptionThrown = (e != null)
    }

    noExceptionThrown
}
4

1 回答 1

2

您可以稍微重新排序代码,这样您就可以使用 Spock 的thrown方法:

def "No exception is thrown"() {
    given:
    def result =  RequestFixture.handle(new TestEndpoint(), { fixture -> fixture.uri("path/a)})

    when:
    result.exception(CustomException)

    then:
    thrown(HandlerExceptionNotThrownException)
}

另一种选择是在测试中使用自定义错误处理程序并将其添加到夹具的注册表中。自定义错误处理程序可以具有指示是否引发异常的方法。请参见以下示例:

package sample

import ratpack.error.ServerErrorHandler
import ratpack.handling.Context
import ratpack.handling.Handler
import ratpack.test.handling.RequestFixture
import spock.lang.Specification

class HandlerSpec extends Specification {

    def 'check exception is thrown'() {
        given:
        def errorHandler = new TestErrorHandler()

        when:
        RequestFixture.handle(new SampleHandler(true), { fixture -> 
            fixture.registry.add ServerErrorHandler, errorHandler
        })

        then:
        errorHandler.exceptionThrown()

        and:
        errorHandler.throwable.message == 'Sample exception'
    }

    def 'check no exception is thrown'() {
        given:
        def errorHandler = new TestErrorHandler()

        when:
        RequestFixture.handle(new SampleHandler(false), { fixture ->
            fixture.registry.add ServerErrorHandler, errorHandler
        })

        then:
        errorHandler.noExceptionThrown()
    }

}

class SampleHandler implements Handler {

    private final boolean throwException = false

    SampleHandler(final boolean throwException) {
        this.throwException = throwException
    }

    @Override
    void handle(final Context ctx) throws Exception {
        if (throwException) {
            ctx.error(new Exception('Sample exception'))
        } else {
            ctx.response.send('OK')
        }
    }

}

class TestErrorHandler implements ServerErrorHandler {

    private Throwable throwable

    @Override
    void error(final Context context, final Throwable throwable) throws Exception {
        this.throwable = throwable
        context.response.status(500)
        context.response.send('NOK')
    }

    boolean exceptionThrown() {
        throwable != null
    }

    boolean noExceptionThrown() {
        !exceptionThrown()
    }
}
于 2017-06-07T05:11:50.543 回答