首页 > 解决方案 > 使用 mockito 在单个测试方法中模拟多个 resttemplate

问题描述

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

标签: javaspring-bootjunitmockito

解决方案


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

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

推荐阅读