This question already has answers here:
How to write a Unit Test?
(5个答案)
How to test a spring controller method by using MockMvc?
(1个答案)
去年关闭。
我有一个GET API,它可以在控制器类中接受不同的参数。根据boolean参数,API应该返回不同的结果。我该如何编写相同的JUnit测试用例?
(5个答案)
How to test a spring controller method by using MockMvc?
(1个答案)
去年关闭。
我有一个GET API,它可以在控制器类中接受不同的参数。根据boolean参数,API应该返回不同的结果。我该如何编写相同的JUnit测试用例?
@CrossOrigin
@RequestMapping(value = "/api/brand/multi-get", method = RequestMethod.GET, consumes =
MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces =
MediaType.APPLICATION_JSON_VALUE)
public ResponseDTO listBrands(@RequestParam(required = false) Integer start,
@RequestParam(required = false) Integer limit,
@RequestParam(required = false) Boolean show_rejected) {
ResponseDTO responseDTO = new ResponseDTO();
System.out.println("------------------");
try {
if (start == null) {
start = 0;
}
if (limit == null) {
limit = 50;
} else if (1 <= limit && limit <= 250) {
if (show_rejected) {
List<Brand> brands = brandService.findAllBrands(start, limit);
if (brands != null && !brands.isEmpty()) {
responseDTO.setData(brands);
responseDTO.setCode(ErrorCode.error_0);
responseDTO.setMessage("Brand list");
return responseDTO;
} else {
responseDTO.setData(new ArrayList<>());
responseDTO.setCode(ErrorCode.error_0);
responseDTO.setMessage("Brand list");
return responseDTO;
}
} else {
Page<Brand> brands = brandService.findAllActiveBrands(start, limit);
if (brands != null && !brands.isEmpty()) {
responseDTO.setData(brands);
responseDTO.setCode(ErrorCode.error_0);
responseDTO.setMessage("Brand list");
return responseDTO;
} else {
responseDTO.setData(new ArrayList<>());
responseDTO.setCode(ErrorCode.error_0);
responseDTO.setMessage("Brand list");
return responseDTO;
}
}
} else {
responseDTO.setCode(ErrorCode.error_1104);
responseDTO.setMessage(ErrorCode.error_msg1104);
return responseDTO;
}
} catch (Exception e) {
e.printStackTrace();
}
return responseDTO;
}
最佳答案
如果您正在使用spring框架并模拟测试,则spring-test库包含MockMvc
和MockMvcRequestBuilders
类,可用于测试任何API。您使用GET API,可以使用
public static MockHttpServletRequestBuilder get(String urlTemplate, Object... uriVars)
中的MockMvcRequestBuilders
方法
然后,您可以使用public ResultActions perform(RequestBuilder requestBuilder)
中的MockMvc
方法来运行该服务。
09-28 07:26