How to test the Service layer in a web service application, using mockite and junit

Asked

Viewed 1,850 times

4

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

The problem is:

I would need to test the service class by calling the REST web service path’s, but I would need to mock the persistence part dependency injection, because right now 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:

@Path("/servico") 
public class Servico() {

    Persistencia persistencia;

    @GET
    @Path("/get")
    @Produces("application/json")
    public Response get(long id) {
        Entidade entidade = persistencia.get(id);
        return Response.ok().entity(entidade).build();
    }
}

3 answers

1

Unit tests are only useful for testing the logic of a class or method. In this case you have a JAX-RS endpoint only, there is no logic there, nor is it advisable to have, this layer specifically should deal only with cases relating to REST. There is no "why" of testing third party Frameworks or lib on your projects, they should already be tested.

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

I advise two frameworks:

  1. Arquillian
  2. Rest Assured

The second is specific for testing for REST endpoints, whereas the first is a much more complete framework, capable of creating "micro deploys", from Dae you can perform tests closer to the production environment. Each has its own particularities of ultimalization (which would be out of the question’s scope).

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 for your class mock Persistencia so you can test public Response get(long id).

  • Thanks Joshua Eduardo for the explanation and the frameworks tips, I’ll take a look at them.

0

0

Use the Spring Mockmvc, with it you can test your REST endpoints, it is interesting that with it you can receive the JSON in return.

Nor need to climb the server, this framework does the abstraction of this and simulates the layer of serialization and deserialization.

I’m on my cell phone right now, I’m doing some research on him, if you have any questions I can send you some very simple examples tomorrow.

If you need just call.

Hugs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.