You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何Mock RestTemplate的getForObject方法?测试报错求助

解决RestTemplate getForObject Mock时的参数匹配器错误

问题原因

你碰到的InvalidUseOfMatchersException是因为MockgetForObject方法时,混用了参数匹配器(ArgumentMatchers.any())和原始值(String.class)。Mockito的规则是:只要使用了参数匹配器,所有参数都必须通过匹配器传递,不能混合原始值和匹配器。

修正方案

1. 统一使用参数匹配器

把第二个参数也换成匹配器,比如用eq(String.class)精确匹配String.class类型,或者用any(Class.class)匹配任意Class类型:

修改测试代码中的when语句:

when(restTemplate.getForObject(ArgumentMatchers.any(),
        ArgumentMatchers.eq(String.class))).thenReturn(xmlString);

2. 确保Mock的RestTemplate实例正确

你的ServiceClient是通过getRestTemplate(RestClientEnum.LOCALIZATION_ZIP.getValue())获取RestTemplate的,必须保证测试中Mock的restTemplate就是这个方法返回的实例。可以在测试初始化时Mock这个方法:

@Mock
private RestTemplate restTemplate;
@InjectMocks
private ServiceClient serviceClient;

@BeforeEach
void setUp() {
    MockitoAnnotations.openMocks(this);
    // 让getRestTemplate返回我们Mock的实例
    when(serviceClient.getRestTemplate(RestClientEnum.LOCALIZATION_ZIP.getValue()))
        .thenReturn(restTemplate);
}

3. 可选:匹配具体URL

如果localizationUrl是固定值,也可以用具体值配合匹配器(同样要保证所有参数都用匹配器):

when(restTemplate.getForObject(ArgumentMatchers.eq("具体的localizationUrl值"),
        ArgumentMatchers.eq(String.class))).thenReturn(xmlString);

修正后的完整测试示例

@Mock
private RestTemplate restTemplate;
@InjectMocks
private ServiceClient serviceClient;
private ZipCodeDetails zipCodeDetails;

@BeforeEach
void setUp() {
    MockitoAnnotations.openMocks(this);
    when(serviceClient.getRestTemplate(RestClientEnum.LOCALIZATION_ZIP.getValue()))
        .thenReturn(restTemplate);
}

@Test
public void validateZipCodeTest() throws Exception {
    String zipCode = "98011";
    String xmlString = "<mockXml>...</mockXml>";
    
    when(restTemplate.getForObject(ArgumentMatchers.any(),
            ArgumentMatchers.eq(String.class))).thenReturn(xmlString);
    
    zipCodeDetails = serviceClient.validateZipCode(zipCode);
    assertNotNull(zipCodeDetails);
}

内容的提问来源于stack exchange,提问作者Krish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 18:18:25