如何使用HttpUnit servlet runner运行servlet测试?启动ServletUnit的问题?

时间:2013-02-22 07:14:08

标签: java http-unit

我计划通过ServletUnit对我的Servlet进行单元测试并遇到一些问题:
- 作为起点,我们应该创建一个ServletRunner对象。其中一个构造函数需要File对象和web.xml文件。我提供了我的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(“Welcome to Leave Management System”));

堆栈跟踪

    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处于root foler,尽管jsp文件存在于... / src / main / webapp /文件夹中。再次告诉ServletUnit目标文件夹位置如何?

非常感谢提前。

最诚挚的问候 M.SuriNaidu

1 个答案:

答案 0 :(得分: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;
    }
}