java - Jetty 在 Java HttpServlet 上总是返回 400 状态代码

标签 java unit-testing servlets junit jetty

我目前正在尝试为 Java 中的 HttpServlet 类设置单元测试。然而,Jetty 文档有点缺乏,我有点卡住了。我相当确定 contextPath 是/hbc,因为我在 servlet 中使用 getContextPath() 将其打印出来。但是,我不确定 a) addServlet() 方法的第二个参数应该是什么,b) URI 应该是什么。

状态码一直返回400,内容为空。我不确定是否是因为我没有指向正确的位置(但我认为这会导致 404)或者是否缺少其他内容。

Servlet 有 init()、processRequest()、doGet() 和 doPost() 方法。

想法?

public class HBCUnitTests extends TestCase {
    private ServletTester tester;

    @BeforeClass
    public void setUp() throws Exception {
        tester = new ServletTester();
        tester.setContextPath("/hbc");
        tester.addServlet(HubCommServlet.class, "/");
        tester.start();
    }

    @AfterClass
    public void tearDown() throws Exception {
        tester.stop();
    }

    @Test
    public void test() throws Exception {
        HttpTester request = new HttpTester();
        request.setMethod("POST");
        request.setVersion("HTTP/1.1");
        request.setURI("/");

        System.out.println(request.generate());

        HttpTester response = new HttpTester();
        response.parse(tester.getResponses(request.generate()));

        System.out.println(response.getContent());
        System.out.println(response.getURI());
        System.out.println(response.getReason());

        assertEquals(200,response.getStatus());
        assertEquals("<h1>Hello Servlet</h1>",response.getContent());
    }
}

最佳答案

看起来 addServlet() 的第二个参数是 servlet 映射。

如果 contextPath 是 /hbc 并且您的 servlet 映射到 / 那么我希望您需要请求 /hbc/:

HttpTester request = new HttpTester();
...
request.setURI("/hbc/");

关于java - Jetty 在 Java HttpServlet 上总是返回 400 状态代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6930629/

相关文章:

c++ - 在 C++ 中使用 Link Seam 打破静态变量依赖

java - 使用 Cross-Context 时获取 servlet 响应

java - 如何在 Spring security 中编辑定时注销

java - MySQL 和 JDBC : What is the safest way to manage multiple schemas?

unit-testing - 什么是 "Stub"?

java - 使用 Mockito 在客户端测试 POST 请求

java - 如何使用 AJAX 将数组从 Servlet 发送到 Javascript?

java - Struts 1.1 和 Servlet 2.5 - 测试期间 JspException 的 NoClassDefFoundError

java - 我们什么时候会在 Spring 中使用 applicationContext.xml?

java - rmi 注册表绑定(bind)问题