簡體   English   中英

模擬的restTemplate.postForObject未在測試執行中使用

[英]Mocked restTemplate.postForObject is not being used in execution of test

我已經使用mickito模擬了一個postForObject resttemplate調用。

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

但是在實際代碼中,沒有使用該模擬值,而是試圖調用遠程位置。

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

根據我的理解,我嘲笑了完全相同的電話。 但是沒有用。 在這方面的任何幫助將是感激的。

我正在自動裝配包含用例類中的測試方法的類。 這個測試類我已經使用new創建了restTemplate。

測試類

@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);  
    }
}

在測試結束時添加一個verify步驟,mockito將為您提供一些提示,告訴您預期的內容和實際的內容:

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

這是我在引用Spring文檔的注釋中所指的示例。

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

    @MockBean
    private RestTemplate restTemplate;

    @Autowired
    private ActionImpl recommendation;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM