2014-03-06 31 views
0

今天我試着寫一個HttpServlet的測試用例。在web.xml中,我定義了一個具有參數名稱和參數值的init參數。我使用了JUnit TestCase。TestSuite for HttpServlet

通過調用這行代碼:

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) 

我想這是因爲東西是不是在網絡容器中運行。令我驚訝的是我無法找到支持HttpServlet的測試套件。我發現Apache仙人掌的StrutsTestCase或ServletTestCase。

我可以用這個測試套件編寫servlet測試用例嗎?我可以使用Mockito來包裝ServletConfig嗎?

回答

0

您會注意到在GenericServlet類中聲明瞭init()方法。它的存在使得子類覆蓋它而不是init(ServletConfig)方法。

該Servlet容器將調用Servlet#init(ServletConfig)方法(其委託HttpServlet子類中的init())。因此,您可以用您最喜歡的模擬框架(Mockito,EasyMock等)來模擬ServletConfig,並將其作爲參數傳遞給init(ServletConfig)方法。