SpringMVC : Controller層單元測試Mock
阿新 • • 發佈:2018-12-11
程式碼
@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);
}
}
配置測試環境
- 在
pom.xml
中匯入Spring test
模組<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.7.RELEASE</version> </dependency>
- 注意 : Spring4 測試的時候,需要
servlet3.0
的支援<dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency>
- 給測試類配置註解
@RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(locations = { "classpath:applicationContext.xml", "file:src/main/webapp/WEB-INF/dispatcherServet-servlet.xml" })
- @RunWith(SpringJUnit4ClassRunner.class) 測試運行於Spring測試環境;
- @ContextConfiguration 載入Spring的配置檔案
- @WebAppConfiguration 表明應該為測試載入WebApplicationContext,
必須
與@ContextConfiguration一起使用 - @Before 編寫
測試方法執行前
的邏輯,可以初始化MockMVC例項
- @Test 標明
實際測試方法
,建議每個Controller
對應一個測試類。
在測試類中,編寫測試邏輯
呼叫 mockMvc.perform
執行模擬請求
- 程式碼來源
MockHttpServletRequestBuilder createMessage = get("/messages").param("pn", "5"); mockMvc.perform(createMessage) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/messages/123"));
- get請求和Controller中的方法請求型別對應
- param為傳遞的引數,允許多個
- andExpect為結果斷言,
- isOk代表的是返回正常也就是http的200,
- view.name為返回的檢視名稱
- andDo為執行後操作,本例的print為打印出結果
- return返回結果,可以對結果進一步操作
關鍵詞
springMVC整合Junit4進行單元測試
、Spring中DAO層介面的單元測試