1. 程式人生 > >Spring MVC測試

Spring MVC測試

簡介
Spring-test技術結合junit,可以說測試專案非常迅速。
我們傳統的技術是寫好程式碼,放在本地的tomcat伺服器或者是其他伺服器中執行,然後拿瀏覽器訪問。這裡面就一個問題,煩。具體將來有兩個缺點。
一 流程複雜,效率低下
二 不能儲存測試資料,進行反覆測試
為此,spring-test結合junit提供了mock物件,完美地解決了上訴兩個問題。
核心類
SpringJUnit4ClassRunner
這個類是spring的單元測試執行類,使用junit的@RunWith註解可以改變預設的單元測試執行類。
@WebAppConfiguration
這個註解是spring webmvc測試必要的一個註解。這個註解就是使得spring單元測試的ApplicationContext的實現為WebApplicationContext型別。WebApplicationContext作為ApplicationContext的其中一個實現,它的獨特性在於包含了ServletContext物件。
@ContextConfiguration


這個註解是配置spring的配置檔案地址或者spring的配置類的類名。有了這個註解SpringJUnit4ClassRunner才能讀取spring配置,從而構建spring的ApplicationContext例項,也就是初始化spring容器。
MockMvc
只有在進行web專案的單元測試才需要這個類。這個類的作用就是判斷,它接收一個URL和一個你預測的結果,然後MockMvc去請求虛擬web伺服器,並將虛擬伺服器返回的結果與預測結果進行對比,以達到測試的目的。
程式碼案例

package springtest;

import org.junit.Before;
import org.junit
.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration
; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = { MyInitializer.class, WebConfig.class }) public class TestController { private MockMvc mockMvc; @Autowired private IndexController indexController; @Before public void setup() { mockMvc = MockMvcBuilders.standaloneSetup(indexController).build(); } @Test public void test() throws Exception { mockMvc.perform(MockMvcRequestBuilders.post("/")) .andExpect(MockMvcResultMatchers.content().string("Hello, 1orld!")); } }

測試結果

java.lang.AssertionError: Response content expected:<Hello, 1orld!> but was:<Hello, world!>

專案原始碼下載地址
技術交流QQ群:69395160
加群連結