适用于HttpServlet的TestSuite

时间:2014-03-06 16:20:58

标签: java unit-testing servlets junit

今天我尝试为HttpServlet编写测试用例。在web.xml中,我使用param name和param值定义了一个init参数。我使用了JUnit TestCase。

通过调用这行代码:

public void init() throws ServletException {
    downloadPath = getServletContext().getRealPath(getInitParameter("downloadPath"));
}

将抛出异常:

java.lang.IllegalStateException: ServletConfig has not been initialized
at javax.servlet.GenericServlet.getServletContext(GenericServlet.java:185)
at com.example.servlet.DownloadServlet.init(DownloadServlet.java:30)

我猜是因为这些东西没有在web容器中运行。令我惊讶的是,我无法找到支持HttpServlet的测试套件。我找到了Apache cactus的StrutsTestCase或ServletTestCase。

我可以用这个测试套件编写servlet测试用例吗?我可以使用Mockito来包装ServletConfig吗?

1 个答案:

答案 0 :(得分:0)

您会注意到init()类中声明了GenericServlet方法。它存在,以便子类覆盖它而不是init(ServletConfig)方法。

Servlet容器将调用Servlet#init(ServletConfig)方法(委托init()个子类中的HttpServlet。)

因此,您可以使用您最喜欢的模拟框架(Mockito,EasyMock等)模拟ServletConfig,并将其作为参数传递给init(ServletConfig)方法。

相关问题