SpringMvc4x高级配置(五) Spring MVC

一. 点睛

测试是保证软件质量的关键,在之前的讲解中只是介绍了简单的测试,下面要进行一些和Spring MVC相关的测试,主要涉及控制器的测试。

为了测试Web项目通常不需要启动项目,我们需要一些Servlet相关的模拟对象,比如:MockMVCMockHttpServletRequestMockHttpServletResponseMockHttpSession等。

Spring里,我们使用@WebAppConfiguration指定加载的ApplicationContext是一个WebAppConfiguration

在下面的示例里面借助JUnitSpring TestContext framework,分别演示对普通页面转向形控制器和RestController进行测试。

二. 示例:

  1. 测试依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
复制代码        <!-- 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>

代码解释:

这里<scope>test</scope>说明这些包的存活是在test周期,也就是意味着发布时我们将不包含这些jar包。

  1. 演示服务:

src/main/java下新增DemoService 类,代码如下所示:

1
2
3
4
5
6
7
8
9
10
11
复制代码package org.light4j.springMvc4.service;

import org.springframework.stereotype.Service;

@Service
public class DemoService {

public String saySomething(){
return "hello";
}
}
  1. 测试用例

src/test/java下新建TestControllerIntegrationTests类,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
复制代码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()进行初始化。
③ 可以在测试用例中注入SpringBean
④ 可注入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

此时,运行该测试,效果如下图所示:
xxx

  1. 编写普通控制器

src/main/java下新增NormalController 类,代码如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
复制代码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";
}
}
  1. 编写普通控制器的演示页面

src/main/resources/view下新建page.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
复制代码<%@ 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>
  1. 编写RestController控制器

src/main/java下新增RestController类,代码如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
复制代码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();
}
}
  1. 运行测试

效果如下图所示:
xxx

三. 源代码示例:

github地址:点击查看
码云地址:点击查看

打赏 欢迎关注人生设计师的微信公众账号
公众号ID:longjiazuoA

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%