Spring Boot中编写单元测试

This commit is contained in:
mrbird 2018-05-02 17:03:13 +08:00
parent 2b182c4fc6
commit 07653c8999
15 changed files with 600 additions and 0 deletions

View File

@ -0,0 +1,80 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" 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">
<modelVersion>4.0.0</modelVersion>
<groupId>demo.springboot</groupId>
<artifactId>Spring-Boot-Testing</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>test</name>
<description>Demo project for Spring Boot test</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.7</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!--通用mapper-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>1.1.5</version>
</dependency>
<!--pagehelper 分页插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>6.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,16 @@
package demo.springboot.test;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication
@EnableTransactionManagement
@MapperScan("demo.springboot.test.mapper")
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}

View File

@ -0,0 +1,8 @@
package demo.springboot.test.config;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {
}

View File

@ -0,0 +1,28 @@
package demo.springboot.test.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import demo.springboot.test.domain.User;
import demo.springboot.test.service.UserService;
@RestController
public class UserController {
@Autowired
UserService userService;
@GetMapping("user/{userName}")
public User getUserByName(@PathVariable(value = "userName") String userName) {
return this.userService.findByName(userName);
}
@PostMapping("user/save")
public void saveUser(@RequestBody User user) {
this.userService.saveUser(user);
}
}

View File

@ -0,0 +1,96 @@
package demo.springboot.test.domain;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name = "T_USER")
public class User {
@Id
@Column(name = "USER_ID")
private Long id;
@Column(name = "USERNAME")
private String username;
@Column(name = "PASSWORD")
private String passwd;
@Column(name = "CRATE_TIME")
private Date createTime;
@Column(name = "STATUS")
private String status;
/**
* @return ID
*/
public Long getId() {
return id;
}
/**
* @param id
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return USERNAME
*/
public String getUsername() {
return username;
}
/**
* @param username
*/
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
/**
* @return PASSWD
*/
public String getPasswd() {
return passwd;
}
/**
* @param passwd
*/
public void setPasswd(String passwd) {
this.passwd = passwd == null ? null : passwd.trim();
}
/**
* @return CREATE_TIME
*/
public Date getCreateTime() {
return createTime;
}
/**
* @param createTime
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
/**
* @return STATUS
*/
public String getStatus() {
return status;
}
/**
* @param status
*/
public void setStatus(String status) {
this.status = status == null ? null : status.trim();
}
}

View File

@ -0,0 +1,9 @@
package demo.springboot.test.mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface SeqenceMapper {
@Select("select ${seqName}.nextval from dual")
Long getSequence(@Param("seqName") String seqName);
}

View File

@ -0,0 +1,7 @@
package demo.springboot.test.mapper;
import demo.springboot.test.config.MyMapper;
import demo.springboot.test.domain.User;
public interface UserMapper extends MyMapper<User> {
}

View File

@ -0,0 +1,27 @@
package demo.springboot.test.service;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;
@Service
public interface IService<T> {
Long getSequence(@Param("seqName") String seqName);
List<T> selectAll();
T selectByKey(Object key);
int save(T entity);
int delete(Object key);
int updateAll(T entity);
int updateNotNull(T entity);
List<T> selectByExample(Object example);
}

View File

@ -0,0 +1,9 @@
package demo.springboot.test.service;
import demo.springboot.test.domain.User;
public interface UserService extends IService<User>{
User findByName(String userName);
void saveUser(User user);
}

View File

@ -0,0 +1,69 @@
package demo.springboot.test.service.impl;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import demo.springboot.test.mapper.SeqenceMapper;
import demo.springboot.test.service.IService;
import tk.mybatis.mapper.common.Mapper;
public abstract class BaseService<T> implements IService<T> {
@Autowired
protected Mapper<T> mapper;
@Autowired
protected SeqenceMapper seqenceMapper;
public Mapper<T> getMapper() {
return mapper;
}
@Override
public Long getSequence(@Param("seqName") String seqName){
return seqenceMapper.getSequence(seqName);
}
@Override
public List<T> selectAll() {
//说明查询所有数据
return mapper.selectAll();
}
@Override
public T selectByKey(Object key) {
//说明根据主键字段进行查询方法参数必须包含完整的主键属性查询条件使用等号
return mapper.selectByPrimaryKey(key);
}
@Override
public int save(T entity) {
//说明保存一个实体null的属性也会保存不会使用数据库默认值
return mapper.insert(entity);
}
@Override
public int delete(Object key) {
//说明根据主键字段进行删除方法参数必须包含完整的主键属性
return mapper.deleteByPrimaryKey(key);
}
@Override
public int updateAll(T entity) {
//说明根据主键更新实体全部字段null值会被更新
return mapper.updateByPrimaryKey(entity);
}
@Override
public int updateNotNull(T entity) {
//根据主键更新属性不为null的值
return mapper.updateByPrimaryKeySelective(entity);
}
@Override
public List<T> selectByExample(Object example) {
//说明根据Example条件进行查询
//重点这个查询支持通过Example类指定查询列通过selectProperties方法指定查询列
return mapper.selectByExample(example);
}
}

View File

@ -0,0 +1,33 @@
package demo.springboot.test.service.impl;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Repository;
import demo.springboot.test.domain.User;
import demo.springboot.test.service.UserService;
import tk.mybatis.mapper.entity.Example;
@Repository("userService")
public class UserServiceImpl extends BaseService<User> implements UserService {
@Override
public User findByName(String userName) {
Example example = new Example(User.class);
example.createCriteria().andCondition("username=", userName);
List<User> userList = this.selectByExample(example);
if (userList.size() != 0)
return userList.get(0);
else
return null;
}
@Override
public void saveUser(User user) {
user.setId(this.getSequence("seq_user"));
user.setCreateTime(new Date());
this.save(user);
}
}

View File

@ -0,0 +1,86 @@
server:
context-path: /web
spring:
datasource:
druid:
# 数据库访问配置, 使用druid数据源
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: oracle.jdbc.driver.OracleDriver
url: jdbc:oracle:thin:@localhost:1521:ORCL
username: test
password: 123456
# 连接池配置
initial-size: 5
min-idle: 5
max-active: 20
# 连接等待超时时间
max-wait: 30000
# 配置检测可以关闭的空闲连接间隔时间
time-between-eviction-runs-millis: 60000
# 配置连接在池中的最小生存时间
min-evictable-idle-time-millis: 300000
validation-query: select '1' from dual
test-while-idle: true
test-on-borrow: false
test-on-return: false
# 打开PSCache并且指定每个连接上PSCache的大小
pool-prepared-statements: true
max-open-prepared-statements: 20
max-pool-prepared-statement-per-connection-size: 20
# 配置监控统计拦截的filters, 去掉后监控界面sql无法统计, 'wall'用于防火墙
filters: stat,wall
# Spring监控AOP切入点如x.y.z.service.*,配置多个英文逗号分隔
aop-patterns: demo.springboot.test.servie.*
# WebStatFilter配置
web-stat-filter:
enabled: true
# 添加过滤规则
url-pattern: /*
# 忽略过滤的格式
exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'
# StatViewServlet配置
stat-view-servlet:
enabled: true
# 访问路径为/druid时跳转到StatViewServlet
url-pattern: /druid/*
# 是否能够重置数据
reset-enable: false
# 需要账号密码才能访问控制台
login-username: druid
login-password: druid123
# IP白名单
# allow: 127.0.0.1
# IP黑名单共同存在时deny优先于allow
# deny: 192.168.1.218
# 配置StatFilter
filter:
stat:
log-slow-sql: true
mybatis:
config-location: classpath:config/mybatis-config.xml
# type-aliases扫描路径
type-aliases-package: demo.springboot.test.domain
# mapper xml实现扫描路径
mapper-locations: classpath:mapper/*.xml
property:
order: BEFORE
#mappers 多个接口时逗号隔开
mapper:
mappers: demo.springboot.test.config.MyMapper
not-empty: false
identity: oracle
#pagehelper
pagehelper:
helperDialect: oracle
reasonable: true
supportMethodsArguments: true
params: count=countSql

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!--解决插入null的时候报错问题-->
<setting name="jdbcTypeForNull" value="NULL"/>
</settings>
</configuration>

View File

@ -0,0 +1,21 @@
-- ----------------------------
-- Table structure for T_USER
-- ----------------------------
CREATE TABLE T_USER (
ID NUMBER NOT NULL ,
USERNAME VARCHAR2(20 BYTE) NOT NULL ,
PASSWD VARCHAR2(128 BYTE) NOT NULL ,
CREATE_TIME DATE NULL ,
STATUS CHAR(1 BYTE) NOT NULL
);
COMMENT ON COLUMN T_USER.USERNAME IS '用户名';
COMMENT ON COLUMN T_USER.PASSWD IS '密码';
COMMENT ON COLUMN T_USER.CREATE_TIME IS '创建时间';
COMMENT ON COLUMN T_USER.STATUS IS '是否有效 1有效 0锁定';
-- ----------------------------
-- Records of T_USER
-- ----------------------------
INSERT INTO T_USER VALUES ('2', 'tester', '243e29429b340192700677d48c09d992', TO_DATE('2017-12-11 17:20:21', 'YYYY-MM-DD HH24:MI:SS'), '1');
INSERT INTO T_USER VALUES ('1', 'mrbird', '42ee25d1e43e9f57119a00d0a39e5250', TO_DATE('2017-12-11 10:52:48', 'YYYY-MM-DD HH24:MI:SS'), '1');
create sequence seq_user start with 1 INCREMENT by 1;

View File

@ -0,0 +1,101 @@
package demo.springboot.test;
import javax.servlet.http.Cookie;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.jsonpath.JsonPath;
import demo.springboot.test.domain.User;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest {
private MockMvc mockMvc;
private MockHttpSession session;
@Autowired
private WebApplicationContext wac;
@Autowired
ObjectMapper mapper;
@Before
public void setupMockMvc(){
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
session = new MockHttpSession();
User user =new User();
user.setUsername("Dopa");
user.setPasswd("ac3af72d9f95161a502fd326865c2f15");
session.setAttribute("user",user);
}
@Test
@Transactional
public void test() throws Exception {
// mockMvc.perform(
// MockMvcRequestBuilders.get("/user/{userName}", "scott")
// .contentType(MediaType.APPLICATION_JSON_UTF8))
// .andExpect(MockMvcResultMatchers.status().isOk())
// .andExpect(MockMvcResultMatchers.jsonPath("$.username").value("scott"))
// .andDo(MockMvcResultHandlers.print());
// String jsonStr = "{\"username\":\"Dopa\",\"passwd\":\"ac3af72d9f95161a502fd326865c2f15\",\"status\":\"1\"}";
User user = new User();
user.setUsername("Dopa");
user.setPasswd("ac3af72d9f95161a502fd326865c2f15");
user.setStatus("1");
String userJson = mapper.writeValueAsString(user);
// mockMvc.perform(MockMvcRequestBuilders.post("/user/save").content(jsonStr.getBytes()));
mockMvc.perform(
MockMvcRequestBuilders.post("/user/save")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(userJson.getBytes()))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
// mockMvc.perform(MockMvcRequestBuilders.get("/hello?name={name}","mrbird"));
// mockMvc.perform(MockMvcRequestBuilders.post("/user/{id}", 1));
// mockMvc.perform(MockMvcRequestBuilders.fileUpload("/fileupload").file("file", "文件内容".getBytes("utf-8")));
// mockMvc.perform(MockMvcRequestBuilders.get("/hello").param("message", "hello"));
// mockMvc.perform(MockMvcRequestBuilders.get("/hobby/save").param("hobby", "sleep", "eat"));
// MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
// params.add("name", "mrbird");
// params.add("hobby", "sleep");
// params.add("hobby", "eat");
// mockMvc.perform(MockMvcRequestBuilders.get("/hobby/save").params(params));
// mockMvc.perform(MockMvcRequestBuilders.get("/index").sessionAttr(name, value));
// mockMvc.perform(MockMvcRequestBuilders.get("/index").cookie(new Cookie(name, value)));
// mockMvc.perform(MockMvcRequestBuilders.get("/index").contentType(MediaType.APPLICATION_JSON_UTF8));
// mockMvc.perform(MockMvcRequestBuilders.get("/user/{id}", 1).accept(MediaType.APPLICATION_JSON));
// mockMvc.perform(MockMvcRequestBuilders.get("/user/{id}", 1).header(name, values));
// mockMvc.perform(MockMvcRequestBuilders.get("/index"))
// .andDo(MockMvcResultHandlers.print());
}
}