I recently found a project where I have to create some unit tests. The problem is that on every method @RestController autowires @Service layer which is fine, but the @Service returns ResponseEntity<?> objects as a result of invoking an external API, an example below:
Rest controller:
@Slf4j
@RestController
public class AppEntryPoint {
@Autowired
MyDirectService myDirectService;
@PostMapping("/create-identity")
public ResponseEntity<?> createIdentity(HttpServletRequest httpServletRequest) throws RestException, IOException {
return myDirectService.createIdentity(httpServletRequest);
}
}
Service:
@Slf4j
@Service
public class MyDirectServiceImpl implements MyDirectService {
@Override
public ResponseEntity<String> createIdentity(HttpServletRequest httpServletRequest) throws RestException, IOException {
String url = "https://mymockserver.com/entity";
return processTransaction(url, httpServletRequest, false);
}
private ResponseEntity<String> processTransaction(String url, HttpServletRequest httpServletRequest, boolean accessToken) throws RestException, IOException {
String requestBody = getRequestBody(httpServletRequest);
HttpHeaders headers = addHeaders(accessToken);
ResponseEntity<String> response = httpUtil.call((url), requestBody, headers);
log.info("Response: {}", response);
return response;
}
}
It seems a bit weird to me using ResponseEntity inside @Service since ResponseEntity is most likely to handle HTTP responses. My concrete questions are:
- Is it correct to use ResponseEntity<> as described in the example?
- How could I create a unit test for @Service layer without using mockMvc? Doesn't make much sense to use it in @Service layer.
Thanks in advance.