Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unit test a servlet with an embedded Jetty

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 request,
        HttpServletResponse response) throws ServletException, IOException {
    //any logic inside
}
like image 502
blue123 Avatar asked Jan 06 '13 05:01

blue123


People also ask

What is embedded Jetty?

Put another way, running Jetty in embedded mode means putting an HTTP module into your application, rather than putting your application into an HTTP server.

Is Jetty a servlet container?

Eclipse Jetty is a Java web server and Java Servlet container. While web servers are usually associated with serving documents to people, Jetty is now often used for machine to machine communications, usually within larger software frameworks.

What is Jetty servlets?

Jetty provides a web server and servlet container, additionally providing support for HTTP/2, WebSocket, OSGi, JMX, JNDI, JAAS and many other integrations. These components are open source and are freely available for commercial use and distribution.

How does Jetty server work?

The Jetty Server is the plumbing between a collection of Connectors that accept HTTP connections, and a collection of Handlers that service requests from the connections and produce responses, with the work being done by threads taken from a thread pool.


1 Answers

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.

like image 94
TheZuck Avatar answered Oct 25 '22 19:10

TheZuck