Jetty always returning 400 status code on Java HttpServlet
I'm currently trying to get a unit test set up for an HttpServlet class I have in Java. However, the Jetty documentation is kind of lacking and I'm a little stuck. I'm fairly certain the contextPath is /hbc as I printed it out using getContextPath() in the servlet. However, I'm not certain what a) the second parameter to the addServlet() method should be and b) what the URI should be.
The status code keeps returning back as 400 and the content is null. I'm not sure if it's because i'm not pointing to the right location (but I would think that would lead to a 404) or if something else is missing.
The servlet has an init(), processRequest(), doGet(), and doPost() method.
Thoughts?
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开发者_如何学C("/");
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());
}
}
It looks like the second argument to addServlet()
is the servlet-mapping.
If the contextPath is /hbc
and your servlet is mapped to /
then I would expect that you need to request /hbc/
:
HttpTester request = new HttpTester();
...
request.setURI("/hbc/");
I ended up using JMock to test the servlet.
精彩评论