Is there a client-side mock framework for RESTEasy?

别等时光非礼了梦想. 提交于 2019-12-06 22:47:14

问题


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.


回答1:


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");
    }
}


来源:https://stackoverflow.com/questions/13631692/is-there-a-client-side-mock-framework-for-resteasy

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