13

我们如何使用嵌入式 Jetty 服务器对 servlet 进行单元测试?

比如下面的servlet方法怎么测试?

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    //any logic inside
}
4

2 回答 2

16

我非常喜欢使用 junit 之类的东西来测试带有 jetty 嵌入式实例的 servlet 来引导它。

http://git.eclipse.org/c/jetty/org.eclipse.jetty.project.git/tree/examples/embedded/src/main/java/org/eclipse/jetty/embedded/MinimalServlets.java

这是如何做到这一点的最小示例。

这也是我们测试绝大多数码头本身的方式,启动它并按照它的速度运行它。

对于特定的 servlet 或处理程序,我们经常在 jetty-test-helper 工件中使用 jetty-client 或 SimpleRequest。URLConnection 也可以。

http://git.eclipse.org/c/jetty/org.eclipse.jetty.toolchain.git/tree/jetty-test-helper/src/main/java/org/eclipse/jetty/toolchain/test/SimpleRequest。爪哇

这是 jetty-client 中的一个测试,它是针对 jetty-9 的,所以如果你想要 7 或 8 然后查看相应的标签,它在 jetty-9 中进行了相当多的重构。

http://git.eclipse.org/c/jetty/org.eclipse.jetty.project.git/tree/jetty-client/src/test/java/org/eclipse/jetty/client/HttpClientTest.java

Note: I recommend you pass 0 as the port for jetty to start up with and that will give you an random open port which you can then pull out of jetty for testing purposes, this avoids the situation where multiple builds are running on CI or parallel builds where there might be a port conflict.

于 2013-01-06T12:05:57.743 回答
2

你不需要Jetty来测试servlet,你需要一个单元测试框架,比如JUnit、Mockito、JMock等。

一般来说,您在进行单元测试时不想使用 servlet 容器,因为您希望将测试重点放在被测试的实际方法上,使用 jetty 意味着您也在测试 jetty 行为。完成所有单元测试后,您可以继续进行集成测试和系统测试,这部分可能涉及外部系统,例如 jetty(使用Selenium等自动化框架。)

我使用 Mockito 和PowerMock进行单元测试,您可以查看此代码以获取真实在线服务的工作示例(您可以在此处找到)。我写了一个关于这个服务的教程和它包含的内容,可以在这里找到。

[在对此答案不时投反对票后添加]:并且冒着获得更多投反对票的风险,所有投反对票的人都需要在单击 -1 按钮之前阅读 UNIT TESTING 的定义。你只是不知道你在说什么。

于 2013-01-06T06:37:35.630 回答