gpt4 book ai didi

java - Spring Boot junit 中 Resttemplate 的 Mocking 失败

转载 作者:行者123 更新时间:2023-11-30 06:03:30 24 4
gpt4 key购买 nike

我正在为调用rest api的方法编写junit测试用例,以下是我尝试过的代码:

@RunWith(MockitoJUnitRunner.class)
public class NotificationApiClientTests {

@Mock
private RestTemplate restTemplate;

@InjectMocks
private NotificationApiClient notificationApiClient;



@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
ReflectionTestUtils.setField(notificationApiClient, "notificationUrl", "myURL***");

}

@Test
public void test_NotificationClickAPI_Call() throws JsonParseException, JsonMappingException, IOException {
ResponseEntity<NotificationClickEvent[]> notificationClickEventList = util.getValidNotificationEvent_ResponseEntity();

Mockito.when(restTemplate.exchange(
Matchers.anyString(),
Matchers.any(HttpMethod.class),
Matchers.<HttpEntity<?>> any(),
Matchers.<Class<NotificationClickEvent[]>> any()
)
).thenReturn(notificationClickEventList);


NotificationClickEvent[] notificationArray = notificationApiClient.requestNotificationClick(Const.NotificationClick, "2018-07-31-10");
assertTrue(notificationArray.length>0);
}
}

在 My NotificationApiClient 中,它是:

@Value("${notification.base.url}")
private String notificationUrl;

public NotificationApiClient() {
}

public UserInfoEvent[] requestUserInfo(String eventType, String dateStr) {
HttpEntity request = new HttpEntity(setHttpHeaders());
ResponseEntity<UserInfoEvent[]> response = this.exchange(
notificationUrl + eventType + "&dateStr=" + dateStr,
HttpMethod.GET, request, UserInfoEvent[].class);
UserInfoEvent[] userInfoRequest = response.getBody();
return userInfoRequest;
}

但它不起作用,根据我的代码,每当调用 resttemplate.exchange 方法时,它应该返回 notificationClickEventList,但它调用真正的 api 并返回 api结果如列表。谁能帮我解决一下吗?

最佳答案

在您的代码中,您没有使用 restTemplate.exchange 方法,看来您正在使用 notificationApiClient 的 exchange 方法。所以试试这个。

@Spy
@InjectMocks
private NotificationApiClient notificationApiClient;


Mockito.when(notificationApiClient.exchange(
Matchers.anyString(),
Matchers.any(HttpMethod.class),
Matchers.<HttpEntity<?>> any(),
Matchers.<Class<NotificationClickEvent[]>> any()
)
).thenReturn(notificationClickEventList);

关于java - Spring Boot junit 中 Resttemplate 的 Mocking 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51816319/

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