java – How to test the Service layer in a web service application, using mockito and join


I have a service class that will receive a dependency injection from an object responsible for the persistence layer. In this service class are all my methods that will respond to the REST call of the web service.

The problem is:

I would need to test the service class, calling the REST web service paths, but I would need to mock the dependency injection of the persistence part, because at this moment I just want to test the service layer. All this using junit and mockito, at most using something like spring. I would like to know from colleagues if this is possible? If yes, an idea of ​​what I should do?

Below an example:

public class Servico() {

    Persistencia persistencia;

    public Response get(long id) {
        Entidade entidade = persistencia.get(id);
        return Response.ok().entity(entidade).build();


Unit tests are only useful for testing the logic of a class or method. In this case you only have a JAX-RS endpoint, there is no logic there, and it's not advisable to have it, this layer specifically should only handle REST-related cases. There is no "why" to test third-party Frameworks or libs in your projects, they must already be tested.

That said, if you really need to, integration testing is the way to go. However, to test all this you have to deploy it inside a container, inevitably, which increases the complexity of the tests.

I advise two frameworks:

  1. arquillian
  2. rest assured

The second is specific for testing REST endpoints, the first is a much more complete Framework, capable of creating "micro deploys", from which you can carry out tests closer to the production environment. Each one has its particularities of use (Which would be outside the scope of the question).

Briefly: If you want to test the REST service really working, only with integration testing in a container, of course. If you need a simple unit test, Mockito would be useful to mock your Persistencia class so you can test public Response get(long id) .

Scroll to Top