用嵌入式Jetty对Servlet进行单元测试 [英] unit test a servlet with an embedded Jetty

查看:104
本文介绍了用嵌入式Jetty对Servlet进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can we unit test a servlet with an embedded Jetty server?

例如,如何测试下面的servlet方法?

For example, how to test the servlet method below?

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

推荐答案

我非常喜欢使用junit之类的东西来测试带有嵌入式码头实例的servlet.

I vastly prefer testing servlets with an embedded instance of jetty using something like junit to bootstrap it.

这是如何执行此操作的最小示例.

that is the minimal example of how to do it.

这也是我们测试绝大多数码头本身,启动并逐步运行的方式.

This is also how we test the vast majority of jetty itself, starting it up and running it through its paces.

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

For a specific servlet or handler we often use the jetty-client or a SimpleRequest in our jetty-test-helper artifact. A URLConnection works as well.

这是在jetty-client中进行的测试,它是针对jetty-9的,因此,如果要7或8,然后在相应的标签下查看,则可以在jetty-9中对其进行大量重构.

Here is a test in the jetty-client, it is for jetty-9 so if you want 7 or 8 then look under the corresponding tag, it was refactored quite a bit in jetty-9.

注意:我建议您将0用作启动码头的端口,这将为您提供一个随机开放的端口,然后您可以将其拉出码头以进行测试,这样可以避免运行多个构建版本的情况CI或并行构建可能存在端口冲突的地方.

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.

这篇关于用嵌入式Jetty对Servlet进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆