gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:43:22 25 4
gpt4 key购买 nike

我正在尝试在 Jersey 测试框架中为身份验证服务编写测试用例,如下所示:

服务代码:

@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)

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

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

最佳答案

您正在使用 Jersey 1.x 测试,但 Entity 仅在 JAX-RS 2.x 中引入,即 Jersey 2.x。 Jersey 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 依赖项,这样您就不会对正在使用的内容感到困惑。

关于java - 在 Jersey 测试框架中测试 Post 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34309999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com