Spring MVC 测试

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 工程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值