latvian
latvian

Reputation: 3215

How to access Body param when MockFor HTTPBuilder

I am writing test that mocks HTTPBuilder. Here is method call that uses the 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);
        }

In the test, i ensure that proper method, contentType and the body parameter is set accordingly.

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

In this test, the assertion for the body.version doesn't work. it gives 'missingPropertyException'. In debug mode, i can see that body parameter has properties 'id' and 'version' but still gives exception. How do i assert for 'body' parameter? Thank You

Upvotes: 0

Views: 647

Answers (1)

latvian
latvian

Reputation: 3215

 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
    }

For more, please, see my post Mock Httpbuilder and POST Requests in Grails

Upvotes: 1

Related Questions