0

我正在编写模拟 HTTPBuilder 的测试。这是使用 HTTBuilder 的方法调用

def http = new HTTPBuilder('http://localhost:8010')
public registerUpdate(Long id, Long version){
        try{
            http.request(Method.POST, JSON){ req ->
                body = [
                        version: version,
                        id: id
                ]

                response.success = {resp, json ->
                    log.warn "cached object id: $id and version: $version; status code: " + resp.statusLine.statusCode
                }
            }
        }catch(Exception e){
            log.warn('Failure Initiate Connection with Node Driver: ' + e.message);
        }

在测试中,我确保相应地设置了正确的方法、contentType 和 body 参数。

def "some test"(){
        setup:
        def httpBuildMock = new MockFor(HTTPBuilder.class)
        httpBuildMock.demand.request{
            met, type, body ->
            assert met == Method.POST
            assert type == ContentType.JSON
            assert 10 == body.version
//            def resp = body.call(null)

        }
        def mockService = httpBuildMock.proxyInstance()
        service.http = mockService

        when:
        service.registerUpdate(1,2)

        then:
        httpBuildMock.verify mockService

在这个测试中,body.version 的断言不起作用。它给出了'missingPropertyException'。在调试模式下,我可以看到 body 参数具有属性 'id' 和 'version' 但仍然给出异常。我如何断言“body”参数?谢谢你

4

1 回答 1

1
 def "ensure params passed in correctly"(){
        setup:
        def httpBuildMock = new MockFor(HTTPBuilder.class)
        def reqPar = []
        def success

        def requestDelegate = [
                response: [:]
        ]

        httpBuildMock.demand.request(1){
            Method met, ContentType type, Closure b ->
            b.delegate = requestDelegate
            b.call()
            reqPar << [method: met, type: type, id: b.body.id, ver: b.body.version ]
        }

        when:
        httpBuildMock.use{
            service.registerUpdate(id,ver)
        }

        then:
        assert reqPar[0].method == Method.POST
        assert reqPar[0].type == ContentType.JSON
        assert reqPar.ver[0] == ver
        assert reqPar.id[0] == id
    }

有关更多信息,请参阅我的帖子Mock Httpbuilder and POST Requests in Grails

于 2013-06-04T02:13:51.197 回答