2016-06-07 95 views
0

所以目前的情况就是这样。我已经构建了一个应用程序,并在控制器上运行了一些测试。然而,测试碰到了实际的第三方API,然后杰克逊对结果进行绑定以映射到POJO对象。Spring MVC模拟第三方API调用

我有点不确定如何嘲笑整个事情,没有我结束人口POJO手动。我正在寻找一些将模拟json响应并将其绑定到POJO的东西,并且我可以验证它是否与模拟json中的数据匹配。

这是我的第三部分,调用API

/** 
* Makes the API call and stores result in POJO 
* It should also gracefully handle any errors 
* @return 
*/ 
public 3rdPartySearchResult searchAPICall(){ 
    if(productQuery==null||productQuery.isEmpty() || productQuery.trim().isEmpty()){ 
     throw new NullPointerException("Query string cannot be empty"); 
    } 
    RestTemplate restTemplate = new RestTemplate(); 
    WalmartSearchResult wsr = restTemplate.getForObject(3rdPartyAPIDetails.searchUrl, 3rdPartyPOJO.class,3rdPartyAPIDetails.APIKey,productQuery); 
    return wsr; 
} 

II某种程度上需要模拟restTemplate.getForObject指向嘲笑JSON文件的样本。

+0

重复:http://stackoverflow.com/questions/32279380/how-to-mock-response-of -rest-通话中弹簧时,你-着-控制研究 - 当 - 的清晰度 –

回答

0

下面的例子测试表明这样做的一种方式,使用JMockit嘲讽库:

@Test 
public void exampleTestForSearchAPICall(@Mocked RestTemplate rest) { 
    SearchAPI searchAPI = new SearchAPI(...productQuery...); 

    3rdPartySearchResult result = searchAPI.searchAPICall(); 

    assertNotNull(result); 

    // Verify the expected call to RestTemplate: 
    new Verifications() {{ rest.getForObject(...argument values and/or matchers...); }}; 
}