开发者

Servlet Testing

开发者 https://www.devze.com 2023-02-04 22:41 出处:网络
I am using the ServletTester class provided by Jetty to test one of my servlets. The servlet reads the the body of the request using InputStream.read() to construct a byte[] which is the decoded and

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

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

The ServletTest class provides a method getResponses(ByteArrayBuffer) but I'm unsure how to create one of these in the correct format since it would also need to contain things like headers (e.g. "Content-Type: application/octet-stream).

Can anyone show me an easy way to construct this, preferably using an existing library so that I can use it in a similar w开发者_运维技巧ay to the HttpTester class.

If there is a "better" way to test servlets (ideally using a local connector rather than via the tcp stack) I'd like to hear that also.

Many thanks,


Why use a mock at all? Why not test the servlet by running it in jetty?

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: Just wanting to reassure people that this is very fast. Its also a very reliable indicator of what your code will actually do, because it is in fact doing it.


Spring MVC provides a small set of "mock" classes for the various javax.servlet interfaces, such as HttpServletRequest, HttpSession, and so on. This makes it easy to unit test the likes of a servlet, you just inject mocks into the e.g. doGet() method.

Even if you don't use Spring itself on the server, you can still use the mock from the library, just for your tests.


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

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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消