【问题标题】:Servlet Testing小服务程序测试
【发布时间】:2011-06-09 06:13:54
【问题描述】:

我正在使用 Jetty 提供的 ServletTester 类来测试我的一个 servlet。

servlet 使用 InputStream.read() 读取请求的主体以构造一个 byte[],该 byte[] 由 servlet 解码并执行。

ServletTest 类提供了一个方法 getResponses(ByteArrayBuffer) 但我不确定如何以正确的格式创建其中一个,因为它还需要包含诸如标头之类的内容(例如“Content-Type: application/octet-stream )。

谁能告诉我一个简单的方法来构建它,最好使用现有的库,这样我就可以像HttpTester 类一样使用它。

如果有一种“更好”的方法来测试 servlet(最好使用本地连接器而不是通过 tcp 堆栈),我也想听听。

非常感谢,

【问题讨论】:

    标签: java testing servlets jetty


    【解决方案1】:

    Spring MVC 为各种javax.servlet 接口提供a small set of "mock" classes,例如HttpServletRequestHttpSession 等。这使得对 servlet 之类的单元测试变得容易,您只需将模拟注入到例如doGet() 方法。

    即使您不在服务器上使用 Spring 本身,您仍然可以使用库中的模拟,仅用于您的测试。

    【讨论】:

      【解决方案2】:

      为什么要使用模拟?为什么不通过在码头运行它来测试 servlet?

      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();
      

      编辑:只是想向人们保证这是非常快的。它也是您的代码实际执行操作的一个非常可靠的指标,因为它实际上正在执行此操作。

      【讨论】:

      • 我看了一下 servlet 测试器,它有点像这样......但我不太喜欢 API。
      【解决方案3】:

      您可以使用 HttpClient 稍微简化测试。看看下面的文章:

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

      结合 servlet 测试器应该可以为您提供您想要的明智的单元测试。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-07
        • 2017-02-01
        • 1970-01-01
        相关资源
        最近更新 更多