1

我打算通过 ServletUnit 对我的 Servlet 进行单元测试,但遇到了一些问题:
- 作为起点,我们应该创建一个 ServletRunner 对象。其中一个构造函数需要带有 web.xml 文件的 File 对象。我提供了我的 web.xml 文件的完整路径,但不知何故它忽略了提供的路径并在顶级文件夹中搜索。代码片段和错误消息如下:

代码片段

    ServletRunner sr = new ServletRunner(new File("* C:/eclipse-workspaces/pocs/lms-csd/src/main/webapp/WEB-INF/web.xml*")); 
ServletUnitClient sc = sr.newClient(); 
 WebRequest request = new PostMethodWebRequest("path to be specified" ); request.setParameter( "userId", "test" );
 request.setParameter( "password", "csd" );
  WebResponse response = sc.getResponse(request);
  String text = response.getText();

Assert.assertTrue(text.contains("欢迎离开管理系统"));

堆栈跟踪

    com.meterware.httpunit.HttpInternalErrorException:
 Error on HTTP request: 500 org.apache.jasper.JasperException: java.io.FileNotFoundException: * C:\eclipse-workspaces\pocs\lms-csd\WEB-INF\web.xml* 
(The system cannot find the path specified)

[http://localhost/login] - 为什么系统一直查看文件夹结构为.../WEB-INF/web.xml。我的项目是一个 Maven 项目,我不想改变项目的结构以适应这种方式。如何使 ServletRunner 类从指定的文件夹中读取?- 在 Servlet 代码中,我使用以下代码:

 String result = null if (someCondition) result = "/welcome.jsp"; } else { logger.warn("Password Validation failed"); request.setAttribute("failedlogin", new Boolean(true)); result = "/index.jsp"; } } RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher(result); requestDispatcher.forward(request, response); 

ServletUnit 再次期望welcome.jsp 位于根目录,尽管jsp 文件存在于.../src/main/webapp/ 文件夹中。同样,如何告知 ServletUnit 目标文件夹位置?

提前谢谢了。

最好的问候 M.SuriNaidu

4

1 回答 1

0

这就是我做的事情。这是我的 servlet 测试的基类的复制品。在这种情况下,我传递了 web.xml 文件的相对路径,因为它存在于我的源代码树中。我从 ant 和 eclipse 运行这些测试。

abstract public class ServletTestCase {

    protected ServletRunner       m_runner;
    protected ServletUnitClient   m_client;
    protected String              m_userAgent = "something/1.0";

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        initHttpUnit();
    }

    @Override
    protected void tearDown() throws Exception {
        shutdownHttpUnit();
        super.tearDown();
    }

    protected void initHttpUnit() throws IOException, SAXException {
        shutdownHttpUnit();

        // We are expecting UTF-8 character handling in URLs, make it the default
        HttpUnitOptions.setDefaultCharacterSet("UTF-8");

        // Find the servlet's web.xml file and use it to init servletunit
        File file = new File("tests/web.xml"));
        m_runner = new ServletRunner(file);
        m_client = m_runner.newClient();
        m_client.getClientProperties().setUserAgent(m_userAgent);
    }

    protected void shutdownHttpUnit() {
        if (m_runner != null) {
            m_runner.shutDown();
        }
        m_client = null;
        m_runner = null;
    }
}
于 2013-02-23T04:59:12.217 回答