1. 程式人生 > >SpringMVC : Controller層單元測試Mock

SpringMVC : Controller層單元測試Mock

程式碼

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "classpath:applicationContext.xml",
		"file:src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml" })
public class MvcTest {
	 
	@Autowired
	WebApplicationContext context;
	 
	MockMvc mockMvc;

	@Before
	public
void initMokcMvc() { mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); } @Test public void testPage() throws Exception { MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/messages").param("pn", "5")) .andReturn(); MockHttpServletRequest request = result.
getRequest(); PageInfo pi = (PageInfo) request.getAttribute("pageInfo"); System.out.println(pi); } }

配置測試環境

  1. pom.xml中匯入 Spring test 模組
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>4.3.7.RELEASE</version>
    </dependency>
    
  2. 注意 : Spring4 測試的時候,需要 servlet3.0的支援
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
    </dependency>        
    
  3. 給測試類配置註解
    @RunWith(SpringJUnit4ClassRunner.class)
    @WebAppConfiguration
    @ContextConfiguration(locations = { "classpath:applicationContext.xml",
            "file:src/main/webapp/WEB-INF/dispatcherServet-servlet.xml" })  
    
    1. @RunWith(SpringJUnit4ClassRunner.class) 測試運行於Spring測試環境;
    2. @ContextConfiguration 載入Spring的配置檔案
    3. @WebAppConfiguration 表明應該為測試載入WebApplicationContext,必須與@ContextConfiguration一起使用
    4. @Before 編寫測試方法執行前的邏輯,可以初始化MockMVC例項
    5. @Test 標明實際測試方法,建議每個Controller對應一個測試類。

在測試類中,編寫測試邏輯

呼叫 mockMvc.perform 執行模擬請求

  1. 程式碼來源
    MockHttpServletRequestBuilder createMessage = 
        get("/messages").param("pn", "5");
    
    mockMvc.perform(createMessage)
        .andExpect(status().is3xxRedirection())
        .andExpect(redirectedUrl("/messages/123"));
    
    1. get請求和Controller中的方法請求型別對應
    2. param為傳遞的引數,允許多個
    3. andExpect為結果斷言,
    4. isOk代表的是返回正常也就是http的200,
    5. view.name為返回的檢視名稱
    6. andDo為執行後操作,本例的print為打印出結果
    7. return返回結果,可以對結果進一步操作

關鍵詞

springMVC整合Junit4進行單元測試Spring中DAO層介面的單元測試