Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a client-side mock framework for RESTEasy?

RESTEasy provides the Server-side Mock Framework for mocking server requests. Is there an equivalent for unit testing the client framework?

Is InMemoryClientExecutor intended for this purpose? I'm having trouble finding documentation and examples of how this class should be used.

like image 887
John McCarthy Avatar asked Nov 29 '12 17:11

John McCarthy


1 Answers

Looks like InMemoryClientExecutor may be used for client-side mocking. Looking in the source, it internally uses the same classes as the server-side mock framework, namely, MockHttpRequest and MockHttpResponse.

InMemoryClientExecutor gives you the ability to override createResponse for mocking responses and also has a constructor which takes a Dispatcher, if you want to customize and intercept calls that way.

Here's a quick and dirty snippet leveraging the client framework example,

import javax.ws.rs.*;
import javax.ws.rs.core.Response.*;

import org.jboss.resteasy.client.*;
import org.jboss.resteasy.client.core.*;
import org.jboss.resteasy.client.core.executors.*;
import org.jboss.resteasy.mock.*;
import org.jboss.resteasy.plugins.providers.*;
import org.jboss.resteasy.spi.*;

public class InMemoryClientExecutorExample {
    public interface SimpleClient {
       @GET
       @Path("basic")
       @Produces("text/plain")
       String getBasic();

       @PUT
       @Path("basic")
       @Consumes("text/plain")
       void putBasic(String body);

       @GET
       @Path("queryParam")
       @Produces("text/plain")
       String getQueryParam(@QueryParam("param")String param);

       @GET
       @Path("matrixParam")
       @Produces("text/plain")
       String getMatrixParam(@MatrixParam("param")String param);

       @GET
       @Path("uriParam/{param}")
       @Produces("text/plain")
       int getUriParam(@PathParam("param")int param);
    }  

    public static void main(String[] args) {
        RegisterBuiltin.register(ResteasyProviderFactory.getInstance());

        ClientExecutor executor = new InMemoryClientExecutor() {
            @Override
            protected BaseClientResponse<?> createResponse(ClientRequest request, MockHttpResponse mockResponse) {
                try {                    
                    System.out.println("Client requesting " + request.getHttpMethod() + " on " + request.getUri());
                }
                catch(Exception ex) {
                    ex.printStackTrace();
                }
                mockResponse.setStatus(Status.OK.getStatusCode());
                return super.createResponse(request, mockResponse);
            }
        };

        SimpleClient client = ProxyFactory.create(SimpleClient.class, "http://localhost:8081", executor);
        client.putBasic("hello world");
    }
}
like image 176
John McCarthy Avatar answered Oct 23 '22 02:10

John McCarthy