gpt4 book ai didi

java - 模棱两可的方法调用模拟 RestTemplate.exchange()

转载 作者:行者123 更新时间:2023-11-30 10:01:35 25 4
gpt4 key购买 nike

无法找出使用匹配器来识别我的目标是交换方法的哪个重载的正确方法。我正在调用的电话:

restTemplate.exchange(url, HttpMethod.PUT, httpEntity, Object.class)

我试过使用任何(Class.class)和其他一些东西,但没有任何效果。我试图区分两种具有相似签名的方法:

exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, Class<T> responseType)

exchange(String var1, HttpMethod var2, @Nullable HttpEntity<?> var3, ParameterizedTypeReference<T> var4)

这是我当前与 Mockito 相关的导入:

import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;

有没有人能够模拟调用这个使用类作为第四个参数而不是 ParameterizedTypeReference 的方法?

最佳答案

我不确定我是否误解了你的问题或 @MarciejKowalski 提到的问题,但是当从问题或我认为类似于你针对 mockito 的示例运行测试时 - core-2.23.4/JDK 1.8.0_151 它工作正常。

[我在您的示例中使用了 JUnit 4 而不是 JUnit 5]

import static org.mockito.ArgumentMatchers.any;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

@RunWith(MockitoJUnitRunner.class)
public class MockitoTest {

@Test
public void test() {

RestTemplate api = Mockito.mock(RestTemplate.class);
ResponseEntity<?> response1 = Mockito.mock(ResponseEntity.class);
ResponseEntity<?> response2 = Mockito.mock(ResponseEntity.class);

Mockito.when(api.exchange(any(String.class), any(HttpMethod.class), any(HttpEntity.class), any(Class.class))).thenReturn(response1);
Mockito.when(api.exchange(any(String.class), any(HttpMethod.class), any(HttpEntity.class), any(ParameterizedTypeReference.class))).thenReturn(response2);

ParameterizedTypeReference mock = Mockito.mock(ParameterizedTypeReference.class);

Assert.assertEquals(response1, api.exchange("", HttpMethod.GET, new HttpEntity(""), String.class));
Assert.assertEquals(response2, api.exchange("", HttpMethod.GET, new HttpEntity(""), mock));
}
}

关于java - 模棱两可的方法调用模拟 RestTemplate.exchange(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57364351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com