I need some help with validation the quality of a controller and unit testing it. Only one parameter is mandatory, rest are Optionals.
In the service class I build a Hibernate criteria.
So my doubts are:
- Is the use of Optionals correct in this case, or would
required=false
be better?
- What and how should be tested here?
- Test should ensure that depending on url's params different results will be returned
- Also, a correct error message should be tested if there is an url problem
- For Service class I tried mocking SessionFactory, Session, but couldn't get it to work
- For Controller class I tried writing Integration test with RestAssured, but I'm not sure how to mock a database / session, how to return and validate a response
- Should I even be testing the service method, as all I do is build a Criteria, and it's not the type I own? In this case, maybe Integration test will be enough?
Controller method:
@RequestMapping(value="/getOrders", method=RequestMethod.GET, produces=MEDIA_JSON_UTF8)
ResponseEntity<Map<String, Object>> getOrders(
@RequestParam("login") String login, @RequestParam("status") Optional<String> status,
@RequestParam("name") Optional<String> name) {
Map<String, Object> result = new HashMap<>();
try {
List<Order> list = ordersService.getOrders(login, status, name);
result.put("data", list);
} catch (CustomException e) {
result.put(ERROR, e.getMessage());
return new ResponseEntity<Map<String,Object>>(result, HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<Map<String,Object>>(result, HttpStatus.OK);
}
}
Service method:
public List<Order> getOrders(String login, Optional<String> status,
Optional<String> name) throws CustomException {
Criteria c = sessionFactory.getCurrentSession()
.createCriteria(Order.class)
.createAlias("seller", "seller")
.add(Restrictions.eq("seller.login", login));
if (status.isPresent()) {
String statusName = status.get();
Status statusObject;
// here I check if statusObject exists
if (null == statusObject) {
throw new CustomException(ERROR_STATUS);
} else {
c.createAlias("status", "status")
.add(Restrictions.eq("status.name", statusName));
}
}
if (name.isPresent()) {
String orderName = name.get();
// here I count if there are any orders with a given name
if (count == 0) {
throw new CustomException(ERROR_NAME + orderName);
} else {
c.add(Restrictions.eq("order_name", orderName));
}
}
List<Order> list = c.list();
return list;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…