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

4

I have a class of services that will receive a dependency injection of 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 path's web service REST, but I would need to mock the dependency injection of the persistence part, because at this point I just want to test the service layer. All this using junit and mockito, at most using something like spring. Would you like to hear from your colleagues if this is possible? If so, what am I supposed to do?

Below is 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();
    }
}
    
asked by anonymous 06.09.2014 / 17:12

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, and neither is advisable to have, this layer specifically should only handle REST-related cases. There is no "why" of testing third-party frameworks or lib in your projects, they should already be tested.

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

I advise two frameworks:

  • Arquillian
  • Rest assured
  • The second is specific to tests for REST endpoints, the first one is a much more complete Framework, able to create "micro deploys", from which you can perform tests closer to the production environment. Each one has its peculiarities of use (which would be outside the scope of the question).

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

        
    06.09.2014 / 23:28
    0

    Look, there is an open source extension for JUnit that is used to test HTTP / REST APIs:

    link

        
    26.12.2014 / 14:05
    0

    Use Spring's MockMVC, with it you can test your REST endpoints, it's interesting that you can get JSON in return.

    No need to upload the server, this framework abstracts from that and simulates the serialization and deserialization layer.

    I'm on the phone now, some of them researched it, if you have questions I can send you some simple examples tomorrow.

    If you need to just call.

    Hugs

        
    16.07.2015 / 04:00