Jetty 的 ServletTester 对于测试 Servlet 应用程序非常有用。我以前使用过 Jetty 6 的 ServletTester,它运行良好。
例如:
码头 6.x
pom.xml
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-servlet-tester</artifactId>
<version>6.1.26</version>
<scope>test</scope>
</dependency>
SampleServletTest.java
package example;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import org.mortbay.jetty.testing.HttpTester;
import org.mortbay.jetty.testing.ServletTester;
public class SampleServletTest {
@Test
public void testDoGet() throws Exception {
ServletTester tester = new ServletTester();
tester.addServlet(SampleServlet.class, "/index");
tester.start();
HttpTester request = new HttpTester();
request.setMethod("GET");
request.setHeader("Host", "tester"); // should be "tester"
request.setURI("/index");
request.setVersion("HTTP/1.1");
request.setContent("");
String responses = tester.getResponses(request.generate());
HttpTester response = new HttpTester();
response.parse(responses);
assertThat(response.getStatus(), is(equalTo(200)));
}
}
码头 9.x
ServletTester 的 API 在 Jetty 9.x 中得到了很大改进。
pom.xml
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>9.0.7.v20131107</version>
<scope>test</scope>
</dependency>
SampleServletTest.java
package example;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import org.eclipse.jetty.http.HttpTester;
import org.eclipse.jetty.servlet.ServletTester;
public class SampleServletTest {
@Test
public void testDoGet() throws Exception {
ServletTester tester = new ServletTester();
tester.addServlet(SampleServlet.class, "/index");
tester.start();
HttpTester.Request request = HttpTester.newRequest();
request.setMethod("GET");
request.setHeader("Host", "tester"); // should be "tester"
request.setURI("/index");
request.setVersion("HTTP/1.1");
request.setContent("");
HttpTester.Response response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertThat(response.getStatus(), is(equalTo(200)));
}
}
新的 API 看起来很酷,但不幸的是上面的代码运行得很慢……这段代码每次运行需要 10 秒。你相信吗?
有没有人知道这个问题?如果这只是我的错误,这是非常好的消息。