2017-06-06 4 views
0

ハンドラユニットテストで、例外がスローされたときに正しくチェックする方法を知っています。RatpackのRequestFixtureとHandlingResultによるユニットテストの例外

しかし、例外がスローされていないことを確認したいときは、正しい方法は何ですか?

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

    when: 
    result.exception(CustomException) 

    then: 
    thrown(HandlerExceptionNotThrownException) 
} 

は別のオプションがされて:あなたはスポックのthrownメソッドを使用できるように

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 
} 

答えて

1

あなたは、少しのコードを並べ替えることができます:

これは私がこれまでに作ってみたが最適ですテストでカスタムエラーハンドラを使用して、フィクスチャのレジストリに追加します。カスタムエラーハンドラには、例外がスローされたかどうかを示すメソッドがあります。 次の例を参照してください。

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() 
    } 
} 
関連する問題