使用RestTemplate exchange方法时抛出InvalidUseOfMatchersException问题
InvalidUseOfMatchersException异常原因及修复
问题重现
运行以下Mockito测试用例时抛出异常:
测试代码
import org.mockito.junit.MockitoJunitRunner; import static org.mockito.Mockito.when; import static org.mockito.ArgumentMatchers.*; @RunWith(MockitoJunitRunner.class) public class APITest{ private RestTemplate restTemplate; private HttpHeaders httpHeaders; private APIService apiService; private String url = "http://sample.com"; private String APIRequestJson = "{ \"text\":\"Greetings\" }"; private String APIResponse; @Before public void setup(){ restTemplate = mock(RestTemplate.class); httpHeaders = mock(HttpHeaders.class); apiService = new APIService(restTemplate,httpHeaders); APIResponse = "{ \"result\":\"ok\" }"; } @Test public void validate_msg_bad_request() { ResponseEntity<?> responseEntity = new ResponseEntity<>(APIResponse, HttpStatus.BAD_REQUEST); when(restTemplate.exchange( anyString(), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class)) ).thenReturn((ResponseEntity<String>) responseEntity); msgResponse = apiService.validateMsg(APIRequestJson, url); Assert.assertequals("400",msgResponse.getStatusCode()); } }
异常信息
Method threw 'org.mockito.exceptions.misusing.InvalidUseOfMatchersException' exception.Cannot evaluate org.springframework.web.client.RestTemplate$MockitoMock$935390488.toString() org.mockito.exceptions.misusing.WrongTypeOfReturnValue: ResponseEntity cannot be returned by toString() toString() should return String
原因分析
不安全的泛型类型转换
创建ResponseEntity<?>实例后强制转为ResponseEntity<String>,这种转换会丢失泛型类型信息,Mockito在处理存根返回值时,无法正确识别返回值的实际类型,进而错误地将ResponseEntity实例关联到某个toString()方法的返回逻辑上(泛型擦除导致内部类型混淆),触发WrongTypeOfReturnValue错误。测试代码的语法问题
msgResponse未声明具体类型,编译器无法正确推断类型,加剧了Mockito的类型识别混乱;- 断言方法名拼写错误(
Assert.assertequals应为Assert.assertEquals),且断言参数类型不匹配(getStatusCode()返回HttpStatus枚举,直接与字符串"400"比较会导致类型不兼容)。
修复方案
1. 修正ResponseEntity的创建方式
直接创建匹配泛型类型的ResponseEntity<String>实例,避免强制转换:
ResponseEntity<String> responseEntity = new ResponseEntity<>(APIResponse, HttpStatus.BAD_REQUEST);
2. 修正存根语句
使用正确类型的返回值,无需强制转换:
when(restTemplate.exchange( anyString(), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class)) ).thenReturn(responseEntity);
3. 修正测试代码的其他问题
- 声明
msgResponse的具体类型; - 修正断言方法名及参数匹配逻辑:
@Test public void validate_msg_bad_request() { ResponseEntity<String> responseEntity = new ResponseEntity<>(APIResponse, HttpStatus.BAD_REQUEST); when(restTemplate.exchange( anyString(), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class)) ).thenReturn(responseEntity); ResponseEntity<String> msgResponse = apiService.validateMsg(APIRequestJson, url); Assert.assertEquals(HttpStatus.BAD_REQUEST, msgResponse.getStatusCode()); // 或按字符串比较 // Assert.assertEquals("400", msgResponse.getStatusCode().toString()); }
内容的提问来源于stack exchange,提问作者CodeLearner
相关产品推荐
相关产品推荐

