Is there a client-side mock framework for RESTEasy?

半腔热情 提交于 2019-12-05 05:24:04

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");
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!