Spring MVC 測試
阿新 • • 發佈:2019-02-16
1、 點睛
為了測試web專案通常不需要啟動專案,我們需要一些servlet相關的模擬物件,比如MockMvc、MockHttpServletRequest、MockHttpServletResponse、MockHttpSession等。
在Spring裡,我們使用 @WebAppConfiguration指定載入的ApplicationContext是一個WebApplicationContext。
下面的示例裡我們藉助Junit和Spring TestContext Framework,分別演示對普通頁面轉向型控制器和RestController進行控制。
2、 示例
1 新增依賴
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring-framework.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency>
2 演示controller
package com.chenfeng.xiaolyuh.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.chenfeng.xiaolyuh.service.DemoService; @RestController public class MyRestController { @Autowired DemoService demoService; @RequestMapping(value = "/testRest" ,produces="text/plain;charset=UTF-8") // @ResponseBody public String testRest(){ return demoService.saySomething(); } }
package com.chenfeng.xiaolyuh.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.chenfeng.xiaolyuh.service.DemoService;
@Controller
public class NormalController {
@Autowired
DemoService demoService;
@RequestMapping("/normal")
public String testPage(Model model){
model.addAttribute("msg", demoService.saySomething());
return "page";
}
}
3 演示服務
package com.chenfeng.xiaolyuh.service;
import org.springframework.stereotype.Service;
@Service
public class DemoService {
public String saySomething() {
return "hello";
}
}
4 演示頁面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test page</title>
</head>
<body>
<pre>
Welcome to Spring MVC world
</pre>
</body>
</html>
5 測試用例,寫在src/test/java下
package com.chenfeng.xiaolyuh.test;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockHttpSession;
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.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.chenfeng.xiaolyuh.config.MvcConfig;
import com.chenfeng.xiaolyuh.service.DemoService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { MvcConfig.class })
@WebAppConfiguration("src/main/resources") // 註解在類上,用來宣告載入的ApplicationContext是一個WebApplicationContext。他的屬性制定的是Web資源的位置,預設是src/main/webapp。
public class TestControllerIntegrationTests {
private MockMvc mockMvc; // 模擬MVC物件,通過MockMvcBuilders.webAppContextSetup(this.wac).build()初始化。
@Autowired
private DemoService demoService; // 可以在測試用例中注入Spring Bean
@Autowired
private WebApplicationContext wac; // 注入WebApplicationContext
@Autowired
private MockHttpSession session;// 注入模擬的http session
@Autowired
private MockHttpServletRequest request;// 注入模擬的http request\
@Before // 在測試開始前初始化工作
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void testNormalController() throws Exception {
mockMvc.perform(get("/normal"))// 模擬向/normal進行get請求
.andExpect(status().isOk())// 預期控制返回狀態是200
.andExpect(view().name("page"))// 預期view名稱是page
.andExpect(forwardedUrl("/WEB-INF/classes/views/page.jsp"))// 預期頁面跳轉的真正路勁是/WEB-INF/classes/views/page.jsp
.andExpect(model().attribute("msg", demoService.saySomething())); // 預期model裡的值是demoService.saySomething()的返回值
}
@Test
public void testRestController() throws Exception {
MvcResult result = mockMvc.perform(get("/testRest")).andExpect(status().isOk())// 模擬向testRest傳送get請求
.andExpect(content().contentType("text/plain;charset=UTF-8"))// 預期返回值的媒體型別text/plain;charset=UTF-8
.andExpect(content().string(demoService.saySomething()))// 預期返回值類容是demoService.saySomething()
.andReturn();// 返回執行請求的結果
System.out.println(result.getResponse());
}
}
原始碼: https://github.com/wyh-spring-ecosystem-student/spring-boot-student/tree/releases
spring-boot-student-data-jpa 工程