在Jersey测试框架中测试Post请求

时间:2015-12-16 10:49:22

标签: java rest junit jersey-test-framework

我正在尝试在Jersey Test Framework中编写一个用于身份验证服务的测试用例,如下所示:

服务代码:

@Path("/users")
@Produces(MediaType.APPLICATION_JSON)
public class AuthenticationServices {
    @POST
    @Path("/login")
    public Response login(LoginRequest loginRequest, @Context HttpServletRequest request) {
       ...... 
     }

Jerysey测试代码:

import java.net.URISyntaxException;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import org.json.JSONException;
import org.junit.Test;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.test.framework.AppDescriptor;
import com.sun.jersey.test.framework.JerseyTest;
import com.sun.jersey.test.framework.WebAppDescriptor;
import com.vs.ant.sensordata.request.LoginRequest;

public class AuthenticationTest extends JerseyTest{
    @Override
    protected AppDescriptor  configure() {
        return new WebAppDescriptor.Builder("com.vs.ant.sensordata.services")
                                .contextPath("anttailbigdata")
                                .build();
    }

    @Test
    @Consumes("application/json")
    public void testLogin() throws JSONException,URISyntaxException {
        WebResource webResource = client().resource("http://localhost:8082/");
        String path = "SensorData/a/users/login";
        LoginRequest loginReq = new LoginRequest();
        loginReq.setUserId("admin");
        loginReq.setPassword("a");
        Entity<LoginRequest> loginEntity = Entity.entity(loginReq, MediaType.APPLICATION_JSON);
        ClientResponse resp = webResource.path(path).post(ClientResponse.class, loginEntity);
    }
}

当尝试执行上述测试时,我得到以下异常:

com.sun.jersey.api.client.ClientHandlerException:  
com.sun.jersey.api.client.ClientHandlerException: A message body writer for Java type, class javax.ws.rs.client.Entity, and MIME media type, application/octet-stream, was not found
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:149)
at com.sun.jersey.api.client.Client.handle(Client.java:648)
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:670)
at com.sun.jersey.api.client.WebResource.post(WebResource.java:251)
at com.vs.ant.sensordata.services.AuthenticationTest.testLogin(AuthenticationTest.java:37)

我是球衣测试的新手。不确定这是否正在发生。请帮忙。

编辑:在方法上方添加@consumes注释。

1 个答案:

答案 0 :(得分:2)

您正在使用Jersey 1.x测试,但Entity仅在JAX-RS 2.x中引入,即Jersey 2.x.泽西岛1.x不知道如何处理它。

而只是发布对象本身,不带任何包装Entity,并通过WebResource#type(..)方法设置它的内容类型。

LoginRequest loginReq = new LoginRequest();
loginReq.setUserId("admin");
loginReq.setPassword("a");
ClientResponse resp = webResource.path(path)
        .type(MediaType.APPLICATION_JSON)
        .post(ClientResponse.class, loginReq);

顺便说一句,如果您使用Jersey 1.x,那么您应该摆脱任何JAX-RS 2.0依赖关系,这样您就不会对自己使用的内容感到困惑。< / p>