2017-06-06 57 views
0

我用mickito嘲笑了postForObject resttemplate調用。 。Mocked restTemplate.postForObject沒有用於執行測試

Mockito.when(restTemplate.postForObject(Mockito.eq(remoteServerlocation),Mockito.any(Input.class),Mockito.eq(String.class)))thenReturn(responseString);

但在實際的代碼中,這個模擬值沒有被使用,並試圖調用遠程位置。

String responseString = restTemplate.postForObject(url,input,String.class);

根據我的理解,我嘲笑完全一樣的電話。但不工作。 對此的任何幫助將感恩。

我自動裝配了包含testcase類中測試方法的類。而這個測試課我使用new創建了restTemplate。

的TestClass

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = Application.class) 
public class ActionImplTest { 

    @Autowired 
    private ActionImpl recommendation; 

    RestTemplate restTemplate = new RestTemplate(); 

    @Test 
    public void performActionTest() throws Exception { 
     String textInput = "InputText"; 
     Map<String, Object> map = new HashMap<String, Object>(); 

     map.put("convId", "C123"); 
     map.put("reID", 1); 
     map.put("chID", "Chann_1"); 

     String convID = "1254356671563"; 
     String chId = "2"; 
     String responseString = "Success" 
     Mockito.when(restTemplate.postForObject(Mockito.eq("remoteServerlocation"), Mockito.any(Input.class), Mockito.eq(String.class))).thenReturn(responseString); 

     Map<String, Object> response = recommendation.performAction(textInput, map, convID, chId); 
    } 
} 

回答

1

添加verify一步在測試結束後,的Mockito會給你什麼預期和實際被稱爲一些提示:

Mockito.verify(restTemplate).postForObject(
    Mockito.eq(remoteServerlocation), Mockito.any(Input.class), Mockito.eq(String.class)); 
+0

我已經這樣做了。但是仍然沒有從這個錯誤報告中得到任何線索。錯誤是說遠程URL上的連接超時 – Parvathy

+0

你是否爲'RestTemplate'創建了一個模擬或間諜?你能提供完整的測試代碼嗎? –

+0

錯誤是說遠程URL上的連接超時---這是調用真正的RestTemplate。你沒有創建模擬/存根。您是否使用模擬(restTemplate)創建restTemplate?看起來像是自動佈線 - 真實場 – xyz

1

這裏是一個我在評論中提到的Spring documentation的例子。

@RunWith(SpringRunner.class) 
@SpringBootTest 
public class ActionImplTest { 

    @MockBean 
    private RestTemplate restTemplate; 

    @Autowired 
    private ActionImpl recommendation;