unit test a servlet with an embedded Jetty

前端 未结 2 756
挽巷
挽巷 2021-02-01 08:48

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

For example, how to test the servlet method below?

protected void doGet(HttpServletRequest          


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-01 09:16

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

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

    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.

    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.

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

    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.

    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.

提交回复
热议问题