SpringBoot - Usage of RestTemplate inside @Service

Viewed 117

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:

  1. Is it correct to use ResponseEntity<> as described in the example?
  2. 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.

1 Answers
  1. I wouldn't, I would leave that for the Controller to do. Services should handle your business model and not specific objects for HTTP responses.
  2. Since MyDirectServiceImpl has no dependency it is a simple unit test. Just instantiate it in your unit test and act upon each of the public methods you want to test and assert their returning values.
Related