2016-06-07 54 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...); }}; 
}