2017-06-06 96 views
0

因此,我知道如何在我的處理程序單元測試中正確檢查何時拋出異常。使用RequestFixture和Ratpack中的HandlingResult進行單元測試異常

但是,當我想確保不拋出異常時,正確的方法是什麼?

這是我想出來的迄今最好的:

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

你可以重新排序的代碼一點,這樣就可以使用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() 
    } 
}