天天看點

Spring MVC單元測試Spring MVC單元測試

Spring MVC單元測試

Spring mvc 測試架構是基于Servlet API mock對象(在spring 的org.springframework.mock.web包中提供),是以無需使用運作時servlet容器。

測試類配置

測試類需要通過注解進行配置,示例代碼如下:

import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.context.ContextConfiguration;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = MyWebConfig.class)
public class MyMvcControllerTest {
....
}
           

@RunWith是JUnit的注解,指定

SpringJUnit4ClassRunner

覆寫确實的

org.junit.runners.BlockJUnit4ClassRunner

,其也是

BlockJUnit4ClassRunner

的子類。

@WebAppConfiguration用于指定為測試加載WebApplicationContext.

@ContextConfiguration用于指定怎麼加載spring bean的中繼資料。上面示例我們指定從MyWebConfig類中加載。

設定@Before對象

在Before注解的方法中,我們需要初始化spring特定的mock對象:MockMvc,spring mvc伺服器端測試支援的主入口。

public class MyMvcControllerTest {

    @Autowired
    private WebApplicationContext wac;
    private MockMvc mockMvc;

    @Before
    public void setup() {
        DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
        this.mockMvc = builder.build();
    }
}
           

MockMvcBuilders 是通路特定MockMvcBuilder的實作接口的主要類。

寫@Test測試方法

這裡我們需要兩個builder 類的協助:

MockMvcRequestBuilders: 用于建構

MockHttpServletRequest

MockMvcResultMatchers: 用于建構

ResultMatcher

,描述比對執行請求期望傳回結果。

@Test
public void testMyMvcController() throws Exception {
   ResultMatcher ok = MockMvcResultMatchers.status().isOk();
   ResultMatcher msg = MockMvcResultMatchers.model()
                       .attribute("msg", "Spring quick start!!");

   MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/");
   this.mockMvc.perform(builder)
               .andExpect(ok)
               .andExpect(msg);
}
           

需要測試的Controller類如下:

@Controller
public class MyMvcController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String prepareView(Model model) {
        model.addAttribute("msg", "Spring quick start!!");
        return "my-page";
    }
}
           

總結

本文介紹了spring mvc 的web請求測試,通過spring mvc提供的mock對象,可以無需servlet運作時容器進行測試。

除了spring test的基本配置以外,還需要添加@WebAppConfiguration,用于加載WebApplicationContext.測試前先在@Before方法中初始化MockMvc mockMvc。最後在兩個builder類的輔助下可以完成web請求的測試。

繼續閱讀