我从未为Spring Boot应用程序编写过JUnit测试。我的服务(localhost)通过RestTemplate
呼叫一个服务,该服务向我发送回复。有人,请给我一个关于我的班级结构的小例子吗?或者有人知道我的案件的文件很好吗?
UIController:
@RequestMapping("/my-service")
public interface MyUIController {
@RequestMapping(method=RequestMethod.GET, value= "/user", produces="application/json")
public List<User> getUser(HttpServletRequest request, HttpServletResponse response);
}
RestController:
@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
?如你所见,我正在呼叫另一项服务。我是否需要制作模拟或者我可以直接从服务中测试我的控制器/服务,我现在正在调用它?
提前致谢!
答案 0 :(得分:2)
最好通过将RestController
getUser()
方法作为端点公开来测试MyUIRestController
。
您可以使用Spring MVC Test框架来测试您的控制器。一个简单的谷歌搜索&#34;春季休息控制器测试&#34;将我重定向到以下链接:
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