测试是保证软件质量的关键,因此在Spring MVC开发软件的过程中或多或少的测试是不可避免的。本文主要进行一些Spring MVC控制器测试的讲解。
为了测试Web项目通常不需要启动项目,我们需要一些Servlet相关的模拟对象,比如:MockMVC,MockHttpServletRequest,MockHttpServletResponse,MockHttpSession等。在Spring里,我们使用@WebAppConfiguration指定加载的ApplicationContext是一个WebAppConfiguration。
在下面的示例里面借助JUnit和Spring TestContext framework,演示对Spring MVC中控制器和RestController的测试。
1. 测试依赖
<!-- spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-framework.version}</version>
<scope>test</scope>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
代码解释:
这里test说明这些包的存活是在test周期,也就是意味着发布时我们将不包含这些jar包。
2. 演示服务:
在src/main/java下新增DemoService 类,代码如下所示:
package org.light4j.springMvc4.service;
import org.springframework.stereotype.Service;
@Service
public class DemoService {
public String saySomething(){
return "hello";
}
}
3. 测试用例
在src/test/java下新建TestControllerIntegrationTests类,代码如下:
package org.light4j.springMvc4.web;
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.light4j.springMvc4.MyMvcConfig;
import org.light4j.springMvc4.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
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.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {MyMvcConfig.class})
@WebAppConfiguration("src/main/resources") //①
public class TestControllerIntegrationTests {
private MockMvc mockMvc; //②
@Autowired
private DemoService demoService;//③
@Autowired
WebApplicationContext wac; //④
@Autowired
MockHttpSession session; //⑤
@Autowired
MockHttpServletRequest request; //⑥
@Before //7
public void setup() {
mockMvc =
MockMvcBuilders.webAppContextSetup(this.wac).build(); //②
}
@Test
public void testNormalController() throws Exception{
mockMvc.perform(get("/normal")) //⑧
.andExpect(status().isOk())//⑨
.andExpect(view().name("page"))//⑩
.andExpect(forwardedUrl("/WEB-INF/classes/views/page.jsp"))//11
.andExpect(model().attribute("msg", demoService.saySomething()));//12
}
@Test
public void testRestController() throws Exception{
mockMvc.perform(get("/testRest")) //13
.andExpect(status().isOk())
.andExpect(content().contentType("text/plain;charset=UTF-8"))//14
.andExpect(content().string(demoService.saySomething()));//15
}
}
代码解释:
① @WebAppConfiguration注解在类上,用来声明加载的ApplicationContext是一个WebApplicationContext。它的属性指定的是Web资源的位置,默认为src/main/webapp,本例修改为src/main/resource。
② MockMvc模拟MVC对象,通过MockMvcBuilders.webAppContextSetup(this.wac).build()进行初始化。
③ 可以在测试用例中注入Spring的Bean。
④ 可注入WebApplicationContext。
⑤ 可注入模拟的http session,此处仅作演示,没有使用。
⑥ 可注入模拟的http request,此处仅作演示,没有使用。
⑦ @Before 在测试开始前进行的初始化工作。
⑧ 模拟向/normal进行get请求。
⑨ 预期控制返回状态为200.
⑩ 预期view的名称为page。
11 预期页面转向的真正路径为/WEB-INF/classes/views/page.jsp。
12 预期model里面的值是demoService.saySomething()返回值hello。
13.模拟向/testRest进行get请求。
14 预期返回值的媒体类型是text/plain;charset=UTF-8。
15 预期返回值的内容为demoService.saySomething()返回值hello。
此时,运行该测试,效果如下图所示:
4. 编写普通控制器
在src/main/java下新增NormalController 类,代码如下所示:
package org.light4j.springMvc4.web;
import org.light4j.springMvc4.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class NormalController {
@Autowired
DemoService demoService;
@RequestMapping("/normal")
public String testPage(Model model){
model.addAttribute("msg", demoService.saySomething());
return "page";
}
}
5. 编写普通控制器的演示页面
在src/main/resources/view下新建page.jsp
<%@ 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>
6. 编写RestController控制器
在src/main/java下新增RestController类,代码如下所示:
package org.light4j.springMvc4.web;
import org.light4j.springMvc4.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@RestController
public class MyRestController {
@Autowired
DemoService demoService;
@RequestMapping(value = "/testRest" ,produces="text/plain;charset=UTF-8")
public @ResponseBody String testRest(){
return demoService.saySomething();
}
}
7. 运行测试
效果如下图所示:
事实上,以上只是Spring MVC中众多测试用例中的一个个例,还有许多的测试用例在本站的Spring MVC视频教程中有详细的说明和讲解,Spring MVC控制器测试也是一个很重要的知识点,有继续深入学习Spring MVC的打算的小伙伴可以参考学习。
QCode09-04 14:38
Code大师09-04 14:50
不写代码你养我啊08-23 11:14
不写代码你养我啊09-17 18:02
要学习了06-18 18:13