我需要为具有多个响应类型不同的多个resttemplate.getForObject()调用的方法编写测试用例。所以我这样写:

@Test
public void tempMethodTest(){
    doReturn(abc).when(restTemplate).getForObject(anyString(), ArgumentMatchers.<Class<ABC>>any());//1st rest call
    doReturn(def).when(restTemplate).getForObject(anyString(), ArgumentMatchers.<Class<DEF>>any());//2nd rest call
    doReturn(efg).when(restTemplate).getForObject(anyString(), ArgumentMatchers.<Class<EFG>>any());//3rd rest call
    //when(restTemplate.getForObject(anyString(), ArgumentMatchers.<Class<ABC>>any())).thenReturn(abc);
    //when(restTemplate.getForObject(anyString(), ArgumentMatchers.<Class<DEF>>any())).thenReturn(def);
    //when(restTemplate.getForObject(anyString(), ArgumentMatchers.<Class<EFG>>any())).thenReturn(efg);

    assertNotNull(service.tempMethod(obj));
}


但是在测试时,我在第一次REST调用中遇到以下提供的异常:

com.example.EFG cannot be cast to com.example.ABC

最佳答案

所以最后我找到了解决这个问题的方法。

@Test
public void getBaseStationConfigurationTest(){
    when(restTemplate.getForObject(anyString(), any())).thenReturn(abc,def,efg);
    assertNotNull(service.tempMethod(obj));
}

10-01 23:39
查看更多