Servlet testing

I am using the ServletTester class provided by Jetty to test one of my servlets.

The servlet reads the body of the request using InputStream.read () to construct the byte [], which is decoded and acted upon by the servlet.

The ServletTest class provides the getResponses (ByteArrayBuffer) method, but I'm not sure how to create one of them in the correct format, since it should also contain things like headers (for example, "Content-Type: application / octet-stream).

Can someone show me an easy way to build this, preferably using an existing library so that I can use it in a similar way to the HttpTester class.

If there is a “better” way to test servlets (ideally using a local connector and not through the tcp stack), I would also like to hear that.

Many thanks,

+3
source share
3 answers

Why use a layout? Why not check out the servlet by running it at the pier?

Servlet servlet = new MyServlet();
String mapping = "/foo";

    Server server = new Server(0);
    Context servletContext = new Context(server, contextPath, Context.SESSIONS);
    servletContext.addServlet(new ServletHolder(servlet), mapping);
    server.start();

    URL url = new URL("http", "localhost", server.getConnectors()[0].getLocalPort(), "/foo?bar");

    //get the url...assert what you want

    //finally server.stop();

Edit: I just want to reassure people that this is very fast. It is also a very reliable indicator of what your code will do, because it really does.

+5
source

Spring MVC provides a small set of “layouts” of classes for various interfaces javax.servlet, such as HttpServletRequest, HttpSessionetc. This makes it easier to unit test like a servlet, you just type mocks in, for example doGet().

Spring , .

+3

You can use HttpClient to simplify testing. Take a look at the following article:

http://roberthanson.blogspot.com/2007/12/testing-servlets-with-junit.html

Which in combination with the servlet tester should give you what you want unit test wise.

+1
source

Source: https://habr.com/ru/post/1785472/


All Articles