Java Servlet單元測試
1. 解決痛點
雖然目前主流的開發方式,很多都是通過controll或者微服務提供api.但是不免還是需要寫幾個servlet
完成接口開發.按照常規,servlet
調用服務層代碼,只需做下服務層單元測試就好了.可是,這里就忽略了請求參數處理過程的測試,按照以往,如果需要測試,往往是先運行一個tomcat,然后找到一個借口測試工具,完成接口測試.其實沒這么麻煩,使用spring-test
即可快速搞定.解決了如下痛點
- 單元測試覆蓋不全面
- 不需要啟動一個servlet容器
- 不需要第三方的接口測試工具
2. 實現方式
既然是做單元測試,首先我們需要在pom文件引入junit
和spring-test
兩個依賴
<!--author:herbert wx:464884492-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${springVersion}</version>
<scope>test</scope>
</dependency>
然后在單元測試的代碼中聲明,我們需要做單元測試的servlet
對象,單元測試類加載時實例化這個對象.
// author:herbert wx:464884492
public class DemoServletTest {
DemoServlet servlet = null;
@Before
public void setUp() {
servlet = new DemoServlet();
DOMConfigurator.configure("src/main/webapp/WEB-INF/log4j.xml");
}
}
再添加我們具體的測試方法,簡單幾句代碼就完成了一個請求封裝.
// author:herbert wx:464884492
@Test
public void testReqImg() throws ServletException, IOException, InterruptedException {
JSONObject p = new JSONObject();
p.put("demoRequest", "herbert 通過spring-test 測試servlet");
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContent(p.toString().getBytes());
MockHttpServletResponse response = new MockHttpServletResponse();
servlet.doPost(request, response);
while (true) {
Thread.sleep(200);
}
}
其實現原理就是 MockHttpServletRequest
和 MockHttpServletResponse
分別實現了接口 HttpServletRequest
和 HttpServletResponse
,一般情況下是,容器自動實現的.所以一般開發時不會注意具體的實現內容.如果感興趣,完全可以自己實現這兩個接口,完成單元測試.
3. 總結
知識雖小,重在積累.2020注定是不平凡的一年.加油!!
歡迎感興趣的朋友關注我的訂閱號“小院不小”,或點擊下方二維碼關注。我將多年開發中遇到的難點,以及一些有意思的功能,體會都會一一發布到我的訂閱號中