gpt4 book ai didi

java - RestTemplate 模拟抛出 NullPointerException

转载 作者:行者123 更新时间:2023-12-02 10:36:04 25 4
gpt4 key购买 nike

我有一个休息模板,它在服务类中的方法中进行调用,如下所示:

public CustomerResponse someMethod() {
CustomerResponse response = restTemplate.exchange(url, HttpMethod.GET, null, CustomerRes.class).getBody();
return response;
}

当尝试在我的测试类中模拟restTemplate时,它不断在调用模拟restTemplate的行上抛出NullPointerException:

public void checkResponseIsNotNull() {
CustomerResponse customerResponseMock = mock(CustomerResponse.class);
when(restTemplate.exchange(url, HttpMethod.GET, null, CustomerResponse.class).getBody()).thenReturn(customerResponseMock);
CustomerResponse cr = service.someMethod();
Assert.assertNotNull(cr);
}

为什么会抛出 NullPointer?我之前模拟过 RestTemplate,只是没有 getBody() 方法,这导致我相信它是导致空指针的原因。

最佳答案

您应该再添加一层模拟:

CustomerResponse customerResponseMock = mock(CustomerResponse.class);
ResponseEntity reMock = mock(ResponseEntity.class);

when(reMock.getBody()).thenReturn(customerResponseMock);
when(restTemplate.exchange(url, HttpMethod.GET, null, CustomerResponse.class)).thenReturn(reMock);

CustomerResponse cr = service.someMethod();

最初,您仅设置了 ResponseEntity,而 RestTemplate 仍保留默认值。因此,当 exchange 已设置时返回 null已调用。

关于java - RestTemplate 模拟抛出 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53284914/

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