我正在编写模拟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'参数?谢谢
答案 0 :(得分: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