JerseyTest失败,因为HttpServletRequest为null

问题描述 投票:0回答:2

我之前使用JerseyTest和一个使用validateSession方法的资源,当资源不使用validateSession时它工作正常,但是使用validateSession扩展类会在测试中抛出500错误。我认为是因为在测试中HttpServletRequest为null。我尝试在相同的方法测试中首先在测试之前进行登录,但是失败了。任何帮助。这是一个简单的资源:

@Path("/test")
public class Prueba extends BaseLoginWebService {

final static Logger logger = Logger.getLogger(Prueba.class);

@GET
public String saludo() {
    return "it works";
  }
}

该资源为了返回String,使用带有validateSession方法的BaseLoginWebService,之前它使用的是LoginWebService:

public class BaseLoginWebService {

@Context
HttpServletRequest request;

final static Logger logger = Logger.getLogger(Prueba.class);

@PostConstruct
public void init() throws Exception {
    validateSession();
}

private void validateSession() throws Exception {
    HttpSession session = request.getSession();
    Cookie[] cookies = request.getCookies();
    String token = null;
    for (Cookie cookie : cookies) {
        if ((cookie.getValue().equals(session.getAttribute("token")))) {
            token = (String) session.getAttribute("token");
            break;
        }
    }
    if (token == null) {
        throw new Exception("no session");
    }
}
}

LoginWebService:

@Path("/login")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class LoginWebService {

@Context
HttpServletRequest request;

@POST
public Response login(LoginEntity loginEntity) {
    if (loginEntity != null) {
        if (loginEntity.getUser().equals("root") && loginEntity.getPassword().equals("root")) {
            HttpSession session = request.getSession();
            session.setMaxInactiveInterval(5);
            Random random = new Random();
            int token = random.nextInt(100) + 1;
            session.setAttribute("token", String.valueOf(token));
            return Response.noContent().cookie(new NewCookie("token", String.valueOf(token))).build();
        } else {
            return Response.status(Response.Status.BAD_REQUEST).build();
        }
    } else {
        return Response.status(Response.Status.CONFLICT).build();
    } 
}
}

资源工作正常,但在测试中没有:

public class PruebaTest extends JerseyTest {

@Override
public Application configure() {
    enable(TestProperties.DUMP_ENTITY);
    enable(TestProperties.LOG_TRAFFIC);
    return new ResourceConfig(Prueba.class);
}

@Override
protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
    return new ExternalTestContainerFactory();
}

@Override
protected URI getBaseUri() {
    URI uri = UriBuilder.fromPath("http://localhost:9090/messenger_webapp/rest").build();
    return uri;
}

@Test
public void saludoTest() {
    System.out.println("saludoTest");
    String output = target("/test").request().get(String.class);
    assertEquals("Should return it works", "it works", output);
}
}

错误:

javax.ws.rs.InternalServerErrorException: HTTP 500 Request failed.

at org.glassfish.jersey.client.JerseyInvocation.convertToException(JerseyInvocation.java:1020)
at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:816) 
  ..... and more .....
java jersey-2.0
2个回答
0
投票

请检查您正在使用的测试容器。根据https://jersey.java.net/nonav/documentation/latest/test-framework.html的文件

内存容器不是真正的容器。它启动Jersey应用程序并直接调用内部API来处理由测试框架提供的客户端创建的请求。没有涉及网络通信。此容器不支持servlet和其他容器相关的功能,但它是简单单元测试的完美选择。

因此,如果您正在使用内存容器并尝试使用servlet功能,那么它将无法工作。在这种情况下,请尝试使用grezzly提供程序或其他与您的最终部署目标相近的内容


0
投票

您尚未提供有关如何部署应用程序的任何详细信息,仅当应用程序部署在servlet容器(例如Tomcat)中时,HttpServletResponse才可用于注入。这可能是你的问题。

我和GrizzlyHttpServer有类似的问题。我的问题的原因是,Grizzly提供了类似于Servlet规范提供的抽象:HttpHandler(Servlet),Request(HttpServletRequest),Response(HttpServletResponse)。

所以我不得不使用:import org.glassfish.grizzly.http.server.Request; 而不是:import javax.servlet.http.HttpServletRequest;

© www.soinside.com 2019 - 2024. All rights reserved.