【问题标题】:Test Request body of restTemplate.postforEntity(url, request,ResponseObj.class)restTemplate.postforEntity(url, request,ResponseObj.class) 的测试请求正文
【发布时间】:2018-10-25 19:06:28
【问题描述】:

如何测试在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 以检查所传递内容的合同

请帮忙。

【问题讨论】:

    标签: spring-mvc junit mockmvc spring-mvc-test springmockito


    【解决方案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());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-02
      • 2019-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多