Spring 单元测试
0. 导入junit 依赖
junit
junit
4.12
test
1. 配置文件
Spring 配置文件
Spring-dao.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
spring-mvc.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
spring-service.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
mybatis 配置文件
database.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.217.82:3306/db_zygy
jdbc.username=root
jdbc.password=1
mybatis-config.xml
/p>
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
Spring 综合配置文件
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
web.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
DispatcherServlet
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:applicationContext.xml
1
DispatcherServlet
*.action
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
utf-8
encodingFilter
/*
GenericEncodingFilter
com.zhiyou100.filter.GenericEncodingFilter
GenericEncodingFilter
/*
path
/Users/yang/Desktop/java26/zygy
key
a1b2
pom.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.zhiyou100
ApartmentInformationManagementSystem
1.0-SNAPSHOT
src/main/java
**/*.properties
**/*.xml
false
src/main/resources
**/*.properties
**/*.xml
false
UTF-8
1.8
4.1.2.RELEASE
8.0.20
org.springframework
spring-context
org.springframework
spring-orm
org.springframework
spring-oxm
org.springframework
spring-jdbc
org.springframework
spring-tx
org.springframework
spring-web
org.springframework
spring-webmvc
org.springframework
spring-aop
org.springframework
spring-test
org.projectlombok
lombok
1.16.20
provided
c3p0
c3p0
0.9.1.2
cn.hutool
hutool-all
4.5.15
com.alibaba
fastjson
1.2.68
mysql
mysql-connector-java
${mysql.version}
dom4j
dom4j
1.6.1
javax.servlet
javax.servlet-api
3.1.0
provided
javax.servlet.jsp
jsp-api
2.1
provided
javax.servlet
jstl
1.2
javax.ws.rs
javax.ws.rs-api
2.0
javax.websocket
javax.websocket-api
1.0
javax.annotation
javax.annotation-api
1.2
javax.transaction
javax.transaction-api
1.2
cglib
cglib
2.2.2
org.mybatis
mybatis
3.4.5
org.mybatis
mybatis-spring
2.0.2
com.github.pagehelper
pagehelper
5.1.10
junit
junit
4.12
test
commons-io
commons-io
2.2
commons-fileupload
commons-fileupload
1.3.1
org.springframework
spring-framework-bom
${spring.version}
pom
import
2. 测试 mapper
LesseeMapper.java
package com.zhiyou100.mapper;
import com.zhiyou100.entity.Lessee;
import java.util.List;
/**
* 组合信息 mapper
*
* @author yang
*/
public interface LesseeMapper {
/**
* 获取所有的租户信息表(Lessee)
*
* @return 所有的租户信息表(Lessee)
*/
List listLessees();
/**
* 根据 lid 获取一个 租户信息表
*
* @param lid 唯一的 id
* @return 根据 id 查找的 租户信息表
*/
Lessee selectOneByLid(Integer lid);
/**
* 根据 传入的 Lessee 更新一个
*
* @param lessee 参数 Lessee
*/
void updateOneLessee(Lessee lessee);
/**
* 根据 cid 删除一个
*
* @param cid 要删除租户信息表的 cid
*/
void deleteOneByCid(Integer cid);
/**
* 添加一个合同
*
* @param lessee 要添加的租户信息表
*/
void insertOne(Lessee lessee);
}
LesseeMapperTest.java
package com.zhiyou100.mapper;
import com.zhiyou100.entity.Lessee;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.transaction.Transactional;
import java.util.Date;
/**
* spring dao 测试
* // @RunWith(SpringJUnit4ClassRunner.class) 必须
* // @ContextConfiguration(locations = {"classpath:applicationContext.xml", "classpath:mybatis-config.xml"}) 加载配置文件
* // @Transactional 单元测试执行完后会撤销对数据库的修改
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml", "classpath:mybatis-config.xml"})
@Transactional
public class LesseeMapperTest {
@Autowired
private LesseeMapper lesseeMapper;
@Test
public void listLessees() {
lesseeMapper.listLessees().forEach(System.out::println);
}
@Test
public void selectOneByLid() {
System.out.println(lesseeMapper.selectOneByLid(1));
}
@Test
public void updateOneLessee() {
final Lessee wang = Lessee.builder()
.lid(1)
.lname("王渊")
.ltel("110")
.lsex("男")
.lnativeplace("郑州")
.lidcard("411323")
.laddtime(new Date())
.build();
lesseeMapper.updateOneLessee(wang);
System.out.println(lesseeMapper.selectOneByLid(1));
}
@Test
public void deleteOneByCid() {
lesseeMapper.deleteOneByCid(1);
System.out.println(lesseeMapper.selectOneByLid(1));
}
@Test
public void insertOne() {
final Lessee wang = Lessee.builder()
.lname("王渊")
.ltel("110")
.lsex("男")
.lnativeplace("郑州")
.lidcard("411323")
.laddtime(new Date())
.build();
lesseeMapper.insertOne(wang);
//for (Lessee listLessee : lesseeMapper.listLessees()) {
// System.err.println(listLessee);
//}
}
@Test
public void insertList(){
int max=100;
for (int i = 0; i < max; i++) {
insertOne();
}
}
}
3. 测试 service
LesseeService.java
package com.zhiyou100.service;
import com.zhiyou100.entity.Lessee;
import java.util.List;
/**
* 租客信息表
*
* @author yang
* @version 1.0.0
* @date 2020-08-31 10:22
*/
public interface LesseeService {
/**
* 获取所有的租户信息表(Lessee)
*
* @return 所有的租户信息表(Lessee)
*/
List listLessees();
/**
* 根据 lid 获取一个 租户信息表
*
* @param lid 唯一的 id
* @return 根据 id 查找的 租户信息表
*/
Lessee selectOneByLid(Integer lid);
/**
* 根据 传入的 Lessee 更新一个
*
* @param lessee 参数 Lessee
*/
void updateOneLessee(Lessee lessee);
/**
* 根据 cid 删除一个
*
* @param cid 要删除租户信息表的 cid
*/
void deleteOneByCid(Integer cid);
/**
* 添加一个合同
*
* @param lessee 要添加的租户信息表
*/
void insertOne(Lessee lessee);
}
LesseeServiceTest.java
package com.zhiyou100.service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.transaction.Transactional;
/**
* service 层测试
* // @RunWith(SpringJUnit4ClassRunner.class) 必须
* * // @ContextConfiguration(locations = {"classpath:applicationContext.xml", "classpath:mybatis-config.xml"}) 加载配置文件
* * // @Transactional 单元测试执行完后会撤销对数据库的修改
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml", "classpath:mybatis-config.xml"})
@Transactional
public class LesseeServiceTest {
@Autowired
private LesseeService lesseeService;
@Test
public void listLessees() {
lesseeService.listLessees().forEach(System.err::println);
}
@Test
public void selectOneByLid() {
}
@Test
public void updateOneLessee() {
}
@Test
public void deleteOneByCid() {
}
@Test
public void insertOne() {
}
}
4. 测试 action
LesseeAction.java
package com.zhiyou100.action;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhiyou100.entity.Lessee;
import com.zhiyou100.service.LesseeService;
import com.zhiyou100.util.object.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* 租客信息 action
*
* @author yang
* @version 1.0.0
* @date 2020-08-31 11:11
*/
@Controller
@RequestMapping("/lessee")
public class LesseeAction {
@Autowired
private LesseeService lesseeService;
@RequestMapping("/list.action")
public String listHouses(Model model,
@RequestParam(defaultValue = "1", value = "pageNo") Integer pageNo
) {
// 每页显示的记录数
int pageSize = 10;
// 分页查询
PageHelper.startPage(pageNo, pageSize);
// 获取所有的信息
final List list = lesseeService.listLessees();
// 使用 PageInfo 结果进行封装
final PageInfo pageInfo = new PageInfo<>(list);
model.addAttribute("pageInfoLessee", pageInfo);
return "view/lessee/list";
}
@RequestMapping("/getOneById.action")
public String getOneByHid(Integer lid, String method, Model model) {
final Lessee lessee = lesseeService.selectOneByLid(lid);
if (lessee != null) {
// 有,放入区域中,跳转 到 详情页面
if (method == null || method.trim().length() == 0) {
// 跳转到 view/lessee/detail
model.addAttribute("lessee", lessee);
return "view/lessee/detail";
} else {
// 跳转到更新界面
model.addAttribute("lessee", lessee);
return "view/lessee/update";
}
} else {
// 没有,返回列表
return "view/lessee/list";
}
}
@RequestMapping("/insertOne.action")
public String insertOne(Lessee lessee, HttpServletRequest request) {
String id = "lid";
String addTime = "laddtime";
if (ObjectUtil.onlyOneFiledIsNullAndTheFiledIsId(lessee, id, addTime)) {
// lid 和 laddtime 字段为空,合法
// 设置时间
lessee.setLaddtime(new Date());
lesseeService.insertOne(lessee);
}
return "/view/lessee/list";
}
@RequestMapping("/updateOne.action")
public String updateOneByCid(Lessee lessee) {
String addTime = "laddtime";
if (ObjectUtil.onlyOneFiledIsNullAndTheFiledIsId(lessee, addTime)) {
// laddtime 字段为空,合法,设置添加时间
lessee.setLaddtime(new Date());
lesseeService.updateOneLessee(lessee);
}
return "/view/lessee/list";
}
/**
* 自定义一个 日期属性编辑器
* yyyy-MM-dd'T'HH:mm:ss 针对
*
* @param request HttpServletRequest
* @param binder binder
*/
@InitBinder
public void myDateBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws UnsupportedEncodingException {
request.setCharacterEncoding("utf-8");
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
binder.registerCustomEditor(Date.class, new CustomDateEditor(simpleDateFormat, true));
}
@RequestMapping("/deleteOneById.action")
public String deleteOneByHid(Integer lid) {
if (lid != null) {
lesseeService.deleteOneByCid(lid);
}
return "view/lessee/list";
}
}
LesseeActionTest.java
package com.zhiyou100.action;
import com.zhiyou100.entity.Lessee;
import com.zhiyou100.service.LesseeService;
import lombok.SneakyThrows;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import javax.transaction.Transactional;
import java.util.Date;
/**
* Controller 测试类
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml", "classpath:mybatis-config.xml"})
@Transactional
public class LesseeActionTest {
@Autowired
private LesseeAction lesseeAction;
@Autowired
private LesseeService lesseeService;
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(lesseeAction).build();
}
@SneakyThrows
@Test
public void listHouses() {
final ResultActions resultActions = this.mockMvc.perform(
MockMvcRequestBuilders
.post("/lessee/list.action")
.param("pageNo", "5")
);
final MvcResult mvcResult = resultActions.andReturn();
// 取出来 request 中的属性
System.out.println(mvcResult.getRequest().getAttribute("pageInfoLessee"));
// 从 response 中取出 状态码
System.out.println("状态码 " + mvcResult.getResponse().getStatus());
}
@SneakyThrows
@Test
public void getOneByHid() {
final ResultActions resultActions = this.mockMvc.perform(
MockMvcRequestBuilders
.post("/lessee/getOneById.action")
.param("lid", "1")
.param("method", "a")
);
// 获取 结果集
final MvcResult mvcResult = resultActions.andReturn();
// 取出来 request 中的属性
System.out.println(mvcResult.getRequest().getAttribute("lessee"));
// 从 response 中取出 状态码
System.out.println("状态码 " + mvcResult.getResponse().getStatus());
System.out.println(mvcResult.getModelAndView().getViewName());
}
@Test
public void insertOne() throws Exception {
final Lessee wang = Lessee.builder()
//.lid(1)
.lname("杨磊")
.ltel("100")
.lsex("男")
.lnativeplace("南阳")
.lidcard("411323")
.laddtime(new Date())
.build();
final ResultActions resultActions = this.mockMvc.perform(
MockMvcRequestBuilders
.post("/lessee/insertOne.action")
.param("lid", "1")
.param("lname", wang.getLname())
.param("ltel", wang.getLtel())
.param("lsex", wang.getLsex())
.param("lnativeplace", wang.getLnativeplace())
.param("lidcard", wang.getLidcard())
//.param("laddtime",wang.getLaddtime())
);
// 获取 结果集
final MvcResult mvcResult = resultActions.andReturn();
// 从 response 中取出 状态码
System.out.println("状态码 " + mvcResult.getResponse().getStatus());
// 获取 视图名字
System.out.println(mvcResult.getModelAndView().getViewName());
// 只要 name 等于 杨磊的
lesseeService.listLessees().stream().filter(lessee ->
lessee.getLname().equalsIgnoreCase("杨磊")
).forEach(System.out::println);
}
@Test
public void updateOneByCid() throws Exception {
System.out.println(System.currentTimeMillis());
final Lessee wang = Lessee.builder()
.lid(1)
.lname("杨磊")
.ltel("100")
.lsex("男")
.lnativeplace("南阳")
.lidcard("411323")
.laddtime(new Date())
.build();
final ResultActions resultActions = this.mockMvc.perform(
MockMvcRequestBuilders
.post("/lessee/updateOne.action")
//.param("lid","1")
.param("lname", wang.getLname())
.param("ltel", wang.getLtel())
.param("lsex", wang.getLsex())
.param("lnativeplace", wang.getLnativeplace())
.param("lidcard", wang.getLidcard())
//.param("laddtime",wang.getLaddtime())
);
// 获取 结果集
final MvcResult mvcResult = resultActions.andReturn();
// 从 response 中取出 状态码
System.out.println("状态码 " + mvcResult.getResponse().getStatus());
// 获取 视图名字
System.out.println(mvcResult.getModelAndView().getViewName());
// 只要 name 等于 杨磊的
//lesseeService.listLessees().stream().filter(lessee ->
// lessee.getLname().equalsIgnoreCase("杨磊")
//).forEach(System.out::println);
System.err.println(lesseeService.selectOneByLid(1));
System.out.println(System.currentTimeMillis());
}
@Test
public void myDateBinder() throws Exception {
}
@Test
public void deleteOneByHid() throws Exception {
System.err.println(lesseeService.selectOneByLid(1));
final ResultActions resultActions = this.mockMvc.perform(
MockMvcRequestBuilders
.post("/lessee/deleteOneById.action")
//.param("lid","")
);
// 获取 结果集
final MvcResult mvcResult = resultActions.andReturn();
// 从 response 中取出 状态码
System.out.println("状态码 " + mvcResult.getResponse().getStatus());
// 获取 视图名字
System.out.println(mvcResult.getModelAndView().getViewName());
System.err.println(lesseeService.selectOneByLid(1));
}
}