unit test a servlet with an embedded Jetty

前端 未结 2 661
挽巷
挽巷 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条回答
  • 2021-02-01 09:12

    You don't need Jetty to test the servlet, you need a unit testing framework, such as JUnit, Mockito, JMock, etc.

    Generally speaking, you don't want to use a servlet container when you do unit testing because you want to focus your test on the actual method being tested, having jetty in the way means that you're also testing jetty behavior. After you've done all your unit tests you can move on to integration tests and system tests, and that part can involve external systems such as jetty (using automation frameworks such as Selenium.)

    I use Mockito and PowerMock to do my unit testing, you can check out this code for a working example of a real online service (which you can find here). I wrote a tutorial about this service and what it contains, this can be found here.

    [Added after getting downvotes from time to time on this answer]: And at the risk of getting even more downvotes, all you downvoters need to read the definition of UNIT TESTING before you click the -1 button. You just don't know what you're talking about.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题