gpt4 book ai didi

spring-boot - 如何在 Mockito 测试中修复 RestTemplate.exchange 的空值响应?

转载 作者:行者123 更新时间:2023-12-01 10:28:06 25 4
gpt4 key购买 nike

我的服务类在下面,然后是它的测试-

@Service
public class MyServiceImpl implements MyService {

@Autowired
private RestTemplate restTemplate;

@Override
public StudentInfo getStudentInfo(String name) {
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);

HttpEntity entity = new HttpEntity(headers);

StudentInfo student = null;

URI uri = new URI("http:\\someurl.com");

ResponseEntity<String> responseEntity = restTemplate.exchange(uri,
HttpMethod.GET, entity,
String.class);

if (responseEntity.getStatusCode().equals(HttpStatus.NO_CONTENT)) {
throw new Exception("Student absent");
}else {
ObjectMapper mapper = new ObjectMapper();
StudentInfo student = mapper.readValue(responseEntity.getBody(), StudentInfo.class);

}

return student;
}
}

测试类:在我下面的测试类中,我在调试时看到 ResponseEntity 对象为空,这会导致 NPE。
@RunWith(MockitoJUnitRunner.class)
public class MyServiceImplTest {

@InjectMocks
private MyService service = new MyServiceImpl();

@Mock
private RestTemplate restTemplate;

@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}

@Test
public void testStudentGetterResponse() {

ResponseEntity<String> mockEntity = Mockito.spy(new ResponseEntity({"id" : 1, "name" : "Rutzen"}, HttpStatus.OK));

doReturn(mockEntity).when(restTemplate).exchange(any(URI.class), any(HttpMethod.class), any(ResponseEntity.class),
any(Class.class));

StudentInfo info = service.getStudentInfo("testuser");

Assert.assertNotNull(info);


}

}

当我调试测试时,我在主服务类的以下行中获得 responseEntity 的空值 -
 ResponseEntity<String> responseEntity = restTemplate.exchange(uri,
HttpMethod.GET, entity,
String.class);

最佳答案

这个指令...

doReturn(mockEntity).when(restTemplate).exchange(
any(URI.class),
any(HttpMethod.class),
any(ResponseEntity.class),
any(Class.class)
);

...应替换为:
doReturn(mockEntity).when(restTemplate).exchange(
any(URI.class),
any(HttpMethod.class),
any(HttpEntity.class),
any(Class.class)
);

因为 getStudentInfo()创建 HttpEntity 的实例( 不是 ResponseEntity )然后传递给 restTemplate.exchange()调用。

关于spring-boot - 如何在 Mockito 测试中修复 RestTemplate.exchange 的空值响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45674149/

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