0

如何测试在 restTemplate.postForEntity 中传递的请求 json。

让我们说以下方法:

    void doAsyncCall(Int id){
        MyObject obj= mydao.getObject(id);
        ///do something 
        MyRequstObject myrequet = constructRequestfromObject(obj);// set some thing in request object form obj

        Myresponse resp = restTemplate.postForEntity(url,new 
        HttpEntitiy(myrequet), respone.class)

        if(resp.status==ok){
            Logger.log("done");
        }
   }

并且在我的测试用例中:-

我想测试在请求中传递给 postForEntity 方法的内容。

1)它更像是我将正确的对象及其属性传递给 post 调用。

2)我们有什么方法可以访问 JUNIT 中的请求 JSON 以检查所传递内容的合同

请帮忙。

4

1 回答 1

1

在您的测试中模拟 restTemplate 并调用doAsyncCall,然后验证是否restTemplate.postForEntity使用正确的参数调用。要断言传递给方法的对象,您可以使用ArgumentCaptor.capture(). 例如:

    ArgumentCaptor<HttpEntity> captor = ArgumentCaptor.forClass(HttpEntity.class);

    verify(restTemplate).postForEntity(eq("some url"), captor.capture(), response.class);
    HttpEntity value = captor.getValue();
    assertEquals("content here", value.getContent());
于 2018-10-25T11:06:28.237 回答