gpt4 book ai didi

java - 如何使用 HttpUnit servlet runner 运行 servlet 测试? ServletUnit 启动时遇到问题?

转载 作者:行者123 更新时间:2023-12-01 04:50:41 25 4
gpt4 key购买 nike

我计划通过 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

最佳答案

这就是我所做的事情。这是我的 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;
}
}

关于java - 如何使用 HttpUnit servlet runner 运行 servlet 测试? ServletUnit 启动时遇到问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15018809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com