Groovy HTTPBuilder Mocking the Response

后端 未结 1 1926
别那么骄傲
别那么骄傲 2020-12-10 14:18

I am trying to figure out how to write my Test cases for a service I am going to write.

The service will use HTTPBuilder to request a response from some URL. The HTT

相关标签:
1条回答
  • 2020-12-10 15:08

    Here's a minimal example of a mock HttpBuilder that will handle your test case:

    class MockHttpBuilder {
        def result
        def requestDelegate = [response: [:]]
    
        def request(Method method, Closure body) {
            body.delegate = requestDelegate
            body.call()
            if (result)
                requestDelegate.response.success()
            else
                requestDelegate.response.failure()
        }
    }
    

    If the result field is true, it'll invoke the success closure, otherwise failure.

    EDIT: Here's an example using MockFor instead of a mock class:

    import groovy.mock.interceptor.MockFor
    
    def requestDelegate = [response: [:]]
    def mock = new MockFor(HttpBuilder)
    mock.demand.request { Method method, Closure body ->
        body.delegate = requestDelegate
        body.call()
        requestDelegate.response.success() // or failure depending on what's being tested
    }
    mock.use {
        assert isOk() == true
    }
    
    0 讨论(0)
提交回复
热议问题