gpt4 book ai didi

java - 如何在 Spring Boot 中为 RestTemplate 编写 JUnit 测试

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

我从未为 Spring Boot 应用程序编写过 JUnit 测试。我的服务 (localhost) 通过 RestTemplate 调用服务,该服务向我发送响应。有人可以给我一个关于我的类(class)结构的小例子吗?或者有人知道我的案例的良好文档吗?

UI Controller :

@RequestMapping("/my-service")
public interface MyUIController {

@RequestMapping(method=RequestMethod.GET, value= "/user", produces="application/json")
public List<User> getUser(HttpServletRequest request, HttpServletResponse response);
}

休息 Controller :

@RestController
public class MyUIRestController implements MyUIController {

@Autowired
private MyUIService myUIService;

public List<User> getUser(HttpServletRequest request, HttpServletResponse response) {
try {
return myUIService.getUser(request, response);
} catch (Exception e) {
e.printStackTrace();
}

return null;
}
}

MyUIService:

@Service
public class MyUIService {
public List<User> getUser(HttpServletRequest request, HttpServletResponse response) throws IOException {

String url = this.webServiceProperties.webUserBaseURL+"searchUser";

MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("firstName", request.getParameter("firstName"));

UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(url).queryParams(params).build().encode();

HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAccept(Collections.singletonList(new MediaType("application","json")));
HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);

RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

ResponseEntity<List<User>> responseEntity = restTemplate.exchange(
uriComponents.toUri(),
HttpMethod.GET, requestEntity,
new ParameterizedTypeReference<List<User>>() {});

return responseEntity.getBody();

}
}

我到底需要测试什么,服务还是RestController?如您所见,我正在调用另一项服务。我是否需要进行模拟,或者我可以直接从我现在正在调用的服务测试我的 Controller /服务吗?

提前致谢!

最佳答案

测试RestController是个好主意。 ,通过公开getUser()你的方法MyUIRestController作为端点。

您可以使用 Spring MVC 测试框架来测试您的 Controller 。简单的谷歌搜索“Spring Rest Controller test”将我重定向到以下链接:

https://www.petrikainulainen.net/programming/spring-framework/unit-testing-of-spring-mvc-controllers-rest-api/

http://blog.zenika.com/2013/01/15/spring-mvc-test-framework/

您还可以引用下面的 Spring 文档:

http://docs.spring.io/spring-security/site/docs/current/reference/html/test-mockmvc.html

关于java - 如何在 Spring Boot 中为 RestTemplate 编写 JUnit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38895901/

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