lichking2017 阅读(101) 评论(0)

from:从0开始,构建前后端分离应用

1. 一些基本概念

1.1 为什么要进行单元测试?我自己的理解是

1、能够快速发现问题。避免衍生BUG的出现
    在对一些现有代码进行修改时,或者修改现有BUG的时候。都有可能对已有的代码产生影响,产生新的问题。那么怎么能避免新问题的产生呢?那就是执行回归测试,但如果是人工进行费时费力,测试的还不全面。况且一般在进度的压力下,相信很少有人会因为修改一个问题而去回归测试以前的功能。
2、前后端分离的基础
    前后端分离的前提就是前后端不互相依赖,前后端的开发是并行的。前端不可能等待后端接口开发完成后在进行页面的开发,后端同样也不能等待页面出来后在开发后端功能。那么调试就成了问题,怎么办?单元测试就解决了这一问题,对于后端来讲,可以使用Mock的方式,模拟request请求,达到测试的目的。
3、发布代码的质量保证
    如果项目是使用Maven管理的,那么根据Maven对项目周期的定义,test是进行打包、部署的前提条件,也就是每次进行打包或者部署,都是经过单元测试的。那么就从出口确保了代码的质量,将发现BUG的时机提前,提高工作效率。

1.2 什么是Mock

1、在单元测试过程中,到处都充满着Mock这个东西,它是什么?
  Mock的英文意思就是模仿、伪装,简单一点儿理解,就是对测试过程中,测试用例对外部的依赖(难以构造的,或者未完成)的一个模仿,在后台的单元测试过程中,可以将难以构造的HttpRequest请求进行Mock。
2、在百度过程中发现了JMockit、Mockito等等,这些都是什么?
  JMockit和Mockito都是用于单元测试的Mock框架,在我的项目里选择的是Mockito

1.3对后台的测试粒度

采用junit+mock+spring-test进行的测试,是对SpringMvc的一个完整的测试,测试过程会包含DispatcherServlet、数据绑定、拦截器等环节,甚至连视图渲染都可以进行测试。是对后台请求的一个完整测试。并且不需要启动tomcat服务器

2. 添加依赖

 1 <dependency>
 2     <groupId>junit</groupId>
 3     <artifactId>junit</artifactId>
 4     <version>${version.junit}</version>
 5     <scope>test</scope>
 6 </dependency>
 7 <dependency>
 8     <groupId>org.springframework</groupId>
 9     <artifactId>spring-test</artifactId>
10     <version>${version.spring}</version>
11     <scope>test</scope>
12     <exclusions>
13         <exclusion>
14             <groupId>org.testng</groupId>
15             <artifactId>testng</artifactId>
16         </exclusion>
17     </exclusions>
18 </dependency>
19 <dependency>
20     <groupId>org.mockito</groupId>
21     <artifactId>mockito-all</artifactId>
22     <version>${version.mockito}</version>
23     <scope>test</scope>
24 </dependency>
25 <dependency>
26     <groupId>org.hamcrest</groupId>
27     <artifactId>hamcrest-all</artifactId>
28     <version>${version.hamcrest}</version>
29     <scope>test</scope>
30 </dependency>

版本信息

<version.mockito>1.10.19</version.mockito>
<version.hamcrest>1.3</version.hamcrest>
<version.junit>4.12</version.junit>
<version.spring>5.0.2.RELEASE</version.spring>
以上需要注意的是hamcrest是需要引入的,否则有可能会报错,junit需要依赖它。它的作用,我们在编写的时候往往是编写断言来判断测试结果,hamcrest是对junit断言的增强,提供更强大的匹配规则,具体参见Hamcrest官网:http://hamcrest.org/JavaHamcrest/

3. 一些注意事项

1、在编写测试用例的时候,往往要编写基类。@RunWith这个注解是不能写在基类中的,否则基类也会被当成测试用例而执行。而基类中是没有任何测试方法的,这时候junit会报错
    有一个变通的方法,@RunWith注解仍然写在基类上,但是为基类增加@Ignore注解,这样在执行Test的时候,就不执行基类了
2、测试代码放在哪个路径下,这里一定注意,卡了我很久。我最开始的时候写在了/project/test/路径下,结果就是无论怎么执行test命令,测试用例都不行,提示“no tests to run”
    正确的方式应该是将测试代码放在/project/src/test/java/路径下

3、在基类中应该做什么事情?
    定义基类的目的,就是将公共的代码抽象到更高的层次。这里包括注解和代码
4、测试过程的环节
    准备测试环境,包括Spring上下文的配置、测试数据、mockMvc初始化、请求头信息的设置、返回预期的设置等
    通过MockMvc执行请求
    使用断言对结果 进行验证

4. 具体实现

BaseTest.java:
1、定义通用注解,由于代码中的注解都是可以继承的,因此完全可以抽象到基类中,避免其他的测试用例重复的声明这些注解
    注意,@Ignore是必须要添加的,否则Maven的surefire插件也会将基类当成一个测试用例来运行,而基类中是没有任何测试方法的,结果就是报错
2、buildResultActions方法中,定义所有请求的通用设置,header信息,及请求结果的期望值,还有对测试过程的打印。其中就使用了hamcrest判断结果中是否包含SUCCESS信息,如果不包含就证明出错了。另外还定义了Session信息,否则后台会因为session中没有用户信息,而将请求拦截住。

 1 package com.wt.test.common;
 2 
 3 import com.google.gson.Gson;
 4 import com.wt.common.security.handler.HttpSessionHandler;
 5 import com.wt.common.security.model.SysUser;
 6 import org.hamcrest.Matchers;
 7 import org.junit.After;
 8 import org.junit.Before;
 9 import org.junit.Ignore;
10 import org.junit.runner.RunWith;
11 import org.slf4j.Logger;
12 import org.slf4j.LoggerFactory;
13 import org.springframework.beans.factory.annotation.Autowired;
14 import org.springframework.http.MediaType;
15 import org.springframework.test.context.ContextConfiguration;
16 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
17 import org.springframework.test.context.web.WebAppConfiguration;
18 import org.springframework.test.web.servlet.MockMvc;
19 import org.springframework.test.web.servlet.ResultActions;
20 import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
21 import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
22 import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
23 import org.springframework.test.web.servlet.setup.MockMvcBuilders;
24 import org.springframework.transaction.annotation.Transactional;
25 import org.springframework.web.context.WebApplicationContext;
26 
27 /**
28  * @ProjectName: syInfo
29  * @Package: com.wt.com.wt.test
30  * @Description:
31  * @Author: lichking2017@aliyun.com
32  * @CreateDate: 2018/5/19 下午5:04
33  * @Version: v1.0
34  */
35 
36 @RunWith(SpringJUnit4ClassRunner.class)
37 @ContextConfiguration(locations = {"classpath:spring.xml", "classpath:spring-mybatis.xml", "classpath:spring-redis.xml"})
38 @WebAppConfiguration
39 @Transactional
40 @Ignore
41 public class BaseTest {
42     Logger logger = LoggerFactory.getLogger(BaseTest.class);
43 
44     @Autowired
45     WebApplicationContext webApplicationContext;
46 
47     protected MockMvc mockMvc;
48 
49     protected SysUser loginUser;
50 
51     protected Gson gson = new Gson();
52 
53     @Before
54     public void setUp() throws Exception {
55         mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
56         loginUser = this.createLoginUser();
57     }
58 
59 
60     /**
61      * 通用设置
62      * @param mhsrb
63      * @return
64      */
65     protected ResultActions buildResultActions(MockHttpServletRequestBuilder mhsrb) {
66         mhsrb.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
67                 .accept(MediaType.APPLICATION_JSON_UTF8_VALUE)
68                 .header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36")
69                 .header("X-Requested-With", "XMLHttpRequest")
70                 .sessionAttr(HttpSessionHandler.Items.LOGINUSER.name(), loginUser);
71         try {
72             return mockMvc
73                     .perform(mhsrb)
74                     .andExpect(MockMvcResultMatchers.status().isOk())
75                     .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
76                     .andExpect(MockMvcResultMatchers.content().string(Matchers.containsString("SUCCESS")))
77                     .andDo(MockMvcResultHandlers.print());
78         } catch (Exception e) {
79             logger.error("请求通用设置出错",e);
80         }
81         return null;
82     }
83 
84 
85     private SysUser createLoginUser() {
86         SysUser sysUser = new SysUser();
87         sysUser.setUserId("0279c9d48c774b5b825dfb6d1058a816");
88         sysUser.setAccount("admin");
89         sysUser.setUserName("系统超级管理员");
90         return sysUser;
91     }
92 
93     @After
94     public void tearDown() throws Exception {
95 
96     }
97 
98 }

测试用例:SysUserControllerTest
1、对于新增用的测试,主要是比对新增前后的表的记录数
2、对更新用户的测试,主要是比对更新后的用户名与要更新的名称是否一致
3、删除用户,也是比对删除前后的记录实现的

  1 package com.wt.common.security.controller;
  2 
  3 import com.wt.common.security.model.SysUser;
  4 import com.wt.common.security.service.SysUserService;
  5 import com.wt.test.common.BaseTest;
  6 import org.hamcrest.Matchers;
  7 import org.junit.Assert;
  8 import org.junit.Test;
  9 import org.springframework.beans.factory.annotation.Autowired;
 10 import org.springframework.test.annotation.Rollback;
 11 import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
 12 
 13 import java.text.SimpleDateFormat;
 14 import java.util.Date;
 15 import java.util.List;
 16 
 17 import static org.hamcrest.MatcherAssert.assertThat;
 18 
 19 /**
 20  * @ProjectName: syInfo
 21  * @Package: com.wt.common.security.controller
 22  * @Description:
 23  * @Author: lichking2017@aliyun.com
 24  * @CreateDate: 2018/5/19 下午5:01
 25  * @Version: v1.0
 26  */
 27 public class SysUserControllerTest extends BaseTest {
 28 
 29     SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
 30 
 31     @Autowired
 32     private SysUserService sysUserService;
 33 
 34     private SysUser sysUser;
 35 
 36     @Override
 37     public void setUp() throws Exception {
 38         super.setUp();
 39         sysUser = this.createSysUser();
 40     }
 41 
 42     @Test
 43     public void findSysUserByUserId() throws Exception {
 44     }
 45 
 46     @Test
 47     @Rollback
 48     public void create() throws Exception {
 49         List<SysUser> sysUsers = sysUserService.selectAll();
 50         int beforCount = sysUsers.size() + 1;
 51         super.buildResultActions(MockMvcRequestBuilders
 52                 .post("/sysUser/create")
 53                 .content(gson.toJson(sysUser)));
 54         List<SysUser> sysUserList = sysUserService.selectAll();
 55         int afterCount = sysUserList.size();
 56         Assert.assertTrue(beforCount == afterCount);
 57     }
 58 
 59     @Test
 60     public void removeUser() throws Exception {
 61         List<SysUser> beforeUsers = sysUserService.selectAll();
 62         int beforCount = beforeUsers.size();
 63         String userId = "";
 64         for (SysUser sysUser : beforeUsers) {
 65             if ("admin".equals(sysUser.getAccount())) {
 66                 continue;
 67             }
 68             userId = sysUser.getUserId();
 69             break;
 70         }
 71 
 72         super.buildResultActions(MockMvcRequestBuilders
 73                 .delete("/sysUser/{userId}", userId)).andReturn();
 74 
 75         List<SysUser> afterUsers = sysUserService.selectAll();
 76         int afterCount = afterUsers.size()+1;
 77         assertThat(beforCount, Matchers.equalTo(afterCount));
 78     }
 79 
 80     @Test
 81     public void update() throws Exception {
 82         try {
 83             List<SysUser> beforeUsers = sysUserService.selectAll();
 84             SysUser forUpdate = new SysUser();
 85             String targetName = simpleDateFormat.format(new Date());
 86 
 87             for (SysUser sysUser : beforeUsers) {
 88                 if ("admin".equals(sysUser.getAccount())) {
 89                     continue;
 90                 }
 91                 forUpdate = sysUser;
 92                 break;
 93             }
 94             String userId = forUpdate.getUserId();
 95             forUpdate.setUserName(targetName);
 96             super.buildResultActions(MockMvcRequestBuilders.put("/sysUser").content(gson.toJson(forUpdate)));
 97             SysUser updatedUser = sysUserService.findById(userId,SysUser.class);
 98             Assert.assertTrue(targetName.equals(updatedUser.getUserName()));
 99         } catch (Exception e) {
100             e.printStackTrace();
101         }
102     }
103 
104     private SysUser createSysUser() {
105         SysUser sysUser = new SysUser();
106         sysUser.setUserName("测试数据" + simpleDateFormat.format(new Date()));
107         sysUser.setPassword("ceshi");
108         sysUser.setAccount(simpleDateFormat.format(new Date()));
109         sysUser.setInUse(true);
110         sysUser.setMail("test@aliyun.com");
111         return sysUser;
112     }
113 }

5. 具体结果

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.wt.test.common.BaseTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 1, Time elapsed: 0.007 sec
Running com.wt.common.security.controller.SysUserControllerTest
2018-05-21 21:02:46,563  INFO WebTestContextBootstrapper:257 - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
2018-05-21 21:02:46,583  INFO WebTestContextBootstrapper:184 - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@217ed35e, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@7dcf94f8, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@229f66ed, org.springframework.test.context.support.DirtiesContextTestExecutionListener@31190526, org.springframework.test.context.transaction.TransactionalTestExecutionListener@662ac478, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@6743e411]
2018-05-21 21:02:46,714  INFO XmlBeanDefinitionReader:316 - Loading XML bean definitions from class path resource [spring.xml]
2018-05-21 21:02:47,012  INFO XmlBeanDefinitionReader:316 - Loading XML bean definitions from class path resource [spring-mybatis.xml]
2018-05-21 21:02:47,058  INFO XmlBeanDefinitionReader:316 - Loading XML bean definitions from class path resource [spring-redis.xml]
2018-05-21 21:02:47,074  INFO GenericWebApplicationContext:589 - Refreshing org.springframework.web.context.support.GenericWebApplicationContext@59af0466: startup date [Mon May 21 21:02:47 CST 2018]; root of context hierarchy
2018-05-21 21:02:47,325  INFO AutowiredAnnotationBeanPostProcessor:154 - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2018-05-21 21:02:48,565  INFO RequestMappingHandlerMapping:549 - Mapped "{[/syslogPerformance/getData],methods=[GET]}" onto public com.wt.common.core.result.HttpResultEntity<?> com.wt.common.security.controller.SyslogPerformanceController.getData()
2018-05-21 21:02:48,571  INFO RequestMappingHandlerMapping:549 - Mapped "{[/sysUser],methods=[PUT]}" onto public com.wt.common.core.result.HttpResultEntity<?> com.wt.common.security.controller.SysUserController.update(com.wt.common.security.model.SysUser)
2018-05-21 21:02:48,571  INFO RequestMappingHandlerMapping:549 - Mapped "{[/sysUser/create],methods=[POST]}" onto public com.wt.common.core.result.HttpResultEntity<?> com.wt.common.security.controller.SysUserController.create(com.wt.common.security.model.SysUser)
2018-05-21 21:02:48,572  INFO RequestMappingHandlerMapping:549 - Mapped "{[/sysUser/login],methods=[GET]}" onto public com.wt.common.core.result.HttpResultEntity<?> com.wt.common.security.controller.SysUserController.login(java.lang.String,java.lang.String) throws com.wt.common.security.exception.BaseSecurityException
2018-05-21 21:02:48,573  INFO RequestMappingHandlerMapping:549 - Mapped "{[/sysUser/userByUserId/{userId}],methods=[GET]}" onto public com.wt.common.core.result.HttpResultEntity<?> com.wt.common.security.controller.SysUserController.findSysUserByUserId(java.lang.String)
2018-05-21 21:02:48,573  INFO RequestMappingHandlerMapping:549 - Mapped "{[/sysUser/{userId}],methods=[DELETE]}" onto public com.wt.common.core.result.HttpResultEntity<?> com.wt.common.security.controller.SysUserController.removeUser(java.lang.String)
2018-05-21 21:02:48,574  INFO RequestMappingHandlerMapping:549 - Mapped "{[/sysUser/userAll],methods=[GET]}" onto public com.wt.common.core.result.HttpResultEntity<?> com.wt.common.security.controller.SysUserController.queryAllUser()
2018-05-21 21:02:48,575  INFO RequestMappingHandlerMapping:549 - Mapped "{[/sysUser/deleteBatch],methods=[DELETE]}" onto public com.wt.common.core.result.HttpResultEntity<?> com.wt.common.security.controller.SysUserController.removeUsers(java.util.List<java.lang.String>)
2018-05-21 21:02:48,576  INFO RequestMappingHandlerMapping:549 - Mapped "{[/sysUser/{id}],methods=[GET]}" onto public com.wt.common.core.result.HttpResultEntity<?> com.wt.common.security.controller.SysUserController.querySysMenu(java.lang.String)
2018-05-21 21:02:48,576  INFO RequestMappingHandlerMapping:549 - Mapped "{[/sysUser/getData],methods=[GET]}" onto public com.wt.common.core.result.HttpResultEntity<?> com.wt.common.security.controller.SysUserController.getData()
2018-05-21 21:02:48,584  INFO RequestMappingHandlerMapping:549 - Mapped "{[/sysMenu],methods=[PUT]}" onto public com.wt.common.core.result.HttpResultEntity<?> com.wt.common.security.controller.SysMenuController.update(com.wt.common.security.model.SysMenu)
2018-05-21 21:02:48,585  INFO RequestMappingHandlerMapping:549 - Mapped "{[/sysMenu/{id}],methods=[DELETE]}" onto public com.wt.common.core.result.HttpResultEntity<?> com.wt.common.security.controller.SysMenuController.delete(java.lang.String)
2018-05-21 21:02:48,586  INFO RequestMappingHandlerMapping:549 - Mapped "{[/sysMenu/create],methods=[POST]}" onto public com.wt.common.core.result.HttpResultEntity<?> com.wt.common.security.controller.SysMenuController.create(com.wt.common.security.model.SysMenu)
2018-05-21 21:02:48,586  INFO RequestMappingHandlerMapping:549 - Mapped "{[/sysMenu/{id}],methods=[GET]}" onto public com.wt.common.core.result.HttpResultEntity<?> com.wt.common.security.controller.SysMenuController.querySysMenu(java.lang.String)
2018-05-21 21:02:48,587  INFO RequestMappingHandlerMapping:549 - Mapped "{[/sysMenu/deleteBatch],methods=[DELETE]}" onto public com.wt.common.core.result.HttpResultEntity<?> com.wt.common.security.controller.SysMenuController.deleteBatch(java.util.List<java.lang.String>)
2018-05-21 21:02:48,588  INFO RequestMappingHandlerMapping:549 - Mapped "{[/sysMenu/queryAdminMenu],methods=[GET]}" onto public com.wt.common.core.result.HttpResultEntity<?> com.wt.common.security.controller.SysMenuController.queryAdminMenu()
2018-05-21 21:02:48,589  INFO RequestMappingHandlerMapping:549 - Mapped "{[/sysMenu/queryAll],methods=[GET]}" onto public com.wt.common.core.result.HttpResultEntity<?> com.wt.common.security.controller.SysMenuController.queryAll()
2018-05-21 21:02:48,590  INFO RequestMappingHandlerMapping:549 - Mapped "{[/sysMenu/getData],methods=[GET]}" onto public com.wt.common.core.result.HttpResultEntity<?> com.wt.common.security.controller.SysMenuController.getData()
2018-05-21 21:02:48,592  INFO RequestMappingHandlerMapping:549 - Mapped "{[/upload/uploadImage],methods=[POST]}" onto public com.wt.common.core.result.HttpResultEntity<?> com.wt.common.upload.controller.UploadFileController.uploadImage(org.springframework.web.multipart.MultipartFile[]) throws com.wt.common.upload.exception.UploadException
2018-05-21 21:02:48,592  INFO RequestMappingHandlerMapping:549 - Mapped "{[/upload/deleteFile/{fileId}],methods=[DELETE]}" onto public com.wt.common.core.result.HttpResultEntity<?> com.wt.common.upload.controller.UploadFileController.deleteFile(java.lang.String)
2018-05-21 21:02:48,762  INFO RequestMappingHandlerAdapter:568 - Looking for @ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext@59af0466: startup date [Mon May 21 21:02:47 CST 2018]; root of context hierarchy
2018-05-21 21:02:48,850  INFO RequestMappingHandlerAdapter:568 - Looking for @ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext@59af0466: startup date [Mon May 21 21:02:47 CST 2018]; root of context hierarchy
2018-05-21 21:02:49,252  INFO DruidDataSource:928 - {dataSource-1} inited
2018-05-21 21:02:49,566  INFO TransactionContext:105 - Began transaction (1) for test context [DefaultTestContext@3ed03652 testClass = SysUserControllerTest, testInstance = com.wt.common.security.controller.SysUserControllerTest@4aedaf61, testMethod = findSysUserByUserId@SysUserControllerTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@173797f0 testClass = SysUserControllerTest, locations = '{classpath:spring.xml, classpath:spring-mybatis.xml, classpath:spring-redis.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[org.springframework.test.context.web.socket.MockServerContainerContextCustomizer@4efbca5a], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.test.context.web.WebDelegatingSmartContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true]]; transaction manager [org.springframework.jdbc.datasource.DataSourceTransactionManager@3c35c345]; rollback [true]
2018-05-21 21:02:49,579  INFO MockServletContext:438 - Initializing Spring FrameworkServlet ''
2018-05-21 21:02:49,579  INFO TestDispatcherServlet:494 - FrameworkServlet '': initialization started
2018-05-21 21:02:49,624  INFO TestDispatcherServlet:513 - FrameworkServlet '': initialization completed in 45 ms
2018-05-21 21:02:49,629  INFO TransactionContext:137 - Rolled back transaction for test context [DefaultTestContext@3ed03652 testClass = SysUserControllerTest, testInstance = com.wt.common.security.controller.SysUserControllerTest@4aedaf61, testMethod = findSysUserByUserId@SysUserControllerTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@173797f0 testClass = SysUserControllerTest, locations = '{classpath:spring.xml, classpath:spring-mybatis.xml, classpath:spring-redis.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[org.springframework.test.context.web.socket.MockServerContainerContextCustomizer@4efbca5a], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.test.context.web.WebDelegatingSmartContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true]].
2018-05-21 21:02:49,632  INFO TransactionContext:105 - Began transaction (1) for test context [DefaultTestContext@3ed03652 testClass = SysUserControllerTest, testInstance = com.wt.common.security.controller.SysUserControllerTest@58496c97, testMethod = create@SysUserControllerTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@173797f0 testClass = SysUserControllerTest, locations = '{classpath:spring.xml, classpath:spring-mybatis.xml, classpath:spring-redis.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[org.springframework.test.context.web.socket.MockServerContainerContextCustomizer@4efbca5a], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.test.context.web.WebDelegatingSmartContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true]]; transaction manager [org.springframework.jdbc.datasource.DataSourceTransactionManager@3c35c345]; rollback [true]
2018-05-21 21:02:49,633  INFO MockServletContext:438 - Initializing Spring FrameworkServlet ''
2018-05-21 21:02:49,633  INFO TestDispatcherServlet:494 - FrameworkServlet '': initialization started
2018-05-21 21:02:49,635  INFO TestDispatcherServlet:513 - FrameworkServlet '': initialization completed in 1 ms
2018-05-21 21:02:49,820  INFO LoginInterceptor:63 - ⭐️{User-Agent:[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36],Protocol:[HTTP/1.1],Remote Addr:[127.0.0.1],Method:[POST],uri:[/sysUser/create],Cookie:[null],operator:[ceshi],parameters:[[{"password":"ceshi","account":"20180521210249","userName":"测试数据20180521210249","inUse":true,"mail":"test@aliyun.com"}]]}⭐️

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /sysUser/create
       Parameters = {}
          Headers = {Content-Type=[application/json;charset=UTF-8], Accept=[application/json;charset=UTF-8], User-Agent=[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36], X-Requested-With=[XMLHttpRequest]}
             Body = {"password":"ceshi","account":"20180521210249","userName":"测试数据20180521210249","inUse":true,"mail":"test@aliyun.com"}
    Session Attrs = {LOGINUSER=com.wt.common.security.model.SysUser@5292ceca}

Handler:
             Type = com.wt.common.security.controller.SysUserController
           Method = public com.wt.common.core.result.HttpResultEntity<?> com.wt.common.security.controller.SysUserController.create(com.wt.common.security.model.SysUser)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {Content-Type=[application/json;charset=UTF-8]}
     Content type = application/json;charset=UTF-8
             Body = {"errorCode":"0","message":"SUCCESS","result":null}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
2018-05-21 21:02:49,907  INFO TransactionContext:137 - Rolled back transaction for test context [DefaultTestContext@3ed03652 testClass = SysUserControllerTest, testInstance = com.wt.common.security.controller.SysUserControllerTest@58496c97, testMethod = create@SysUserControllerTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@173797f0 testClass = SysUserControllerTest, locations = '{classpath:spring.xml, classpath:spring-mybatis.xml, classpath:spring-redis.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[org.springframework.test.context.web.socket.MockServerContainerContextCustomizer@4efbca5a], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.test.context.web.WebDelegatingSmartContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true]].
2018-05-21 21:02:49,910  INFO TransactionContext:105 - Began transaction (1) for test context [DefaultTestContext@3ed03652 testClass = SysUserControllerTest, testInstance = com.wt.common.security.controller.SysUserControllerTest@62e93c3a, testMethod = update@SysUserControllerTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@173797f0 testClass = SysUserControllerTest, locations = '{classpath:spring.xml, classpath:spring-mybatis.xml, classpath:spring-redis.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[org.springframework.test.context.web.socket.MockServerContainerContextCustomizer@4efbca5a], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.test.context.web.WebDelegatingSmartContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true]]; transaction manager [org.springframework.jdbc.datasource.DataSourceTransactionManager@3c35c345]; rollback [true]
2018-05-21 21:02:49,911  INFO MockServletContext:438 - Initializing Spring FrameworkServlet ''
2018-05-21 21:02:49,911  INFO TestDispatcherServlet:494 - FrameworkServlet '': initialization started
2018-05-21 21:02:49,913  INFO TestDispatcherServlet:513 - FrameworkServlet '': initialization completed in 1 ms
2018-05-21 21:02:49,938  INFO LoginInterceptor:63 - ⭐️{User-Agent:[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36],Protocol:[HTTP/1.1],Remote Addr:[127.0.0.1],Method:[PUT],uri:[/sysUser],Cookie:[null],operator:[ceshi],parameters:[[{"userId":"6057e4e4da6542f2bc32de5a43096dcd","password":"zBfDDNERxyFfyPUfh5Dg4Q\u003d\u003d","account":"20180521142248","userName":"20180521210249","inUse":true,"mail":"test@aliyun.com","creator":"099","changedBy":"099","lastUpdate":"2018-05-20","deleteFlag":false}]]}⭐️

MockHttpServletRequest:
      HTTP Method = PUT
      Request URI = /sysUser
       Parameters = {}
          Headers = {Content-Type=[application/json;charset=UTF-8], Accept=[application/json;charset=UTF-8], User-Agent=[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36], X-Requested-With=[XMLHttpRequest]}
             Body = {"userId":"6057e4e4da6542f2bc32de5a43096dcd","password":"zBfDDNERxyFfyPUfh5Dg4Q\u003d\u003d","account":"20180521142248","userName":"20180521210249","inUse":true,"mail":"test@aliyun.com","creator":"099","changedBy":"099","lastUpdate":"2018-05-20","deleteFlag":false}
    Session Attrs = {LOGINUSER=com.wt.common.security.model.SysUser@292158f8}

Handler:
             Type = com.wt.common.security.controller.SysUserController
           Method = public com.wt.common.core.result.HttpResultEntity<?> com.wt.common.security.controller.SysUserController.update(com.wt.common.security.model.SysUser)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {Content-Type=[application/json;charset=UTF-8]}
     Content type = application/json;charset=UTF-8
             Body = {"errorCode":"0","message":"SUCCESS","result":null}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
2018-05-21 21:02:49,958  INFO TransactionContext:137 - Rolled back transaction for test context [DefaultTestContext@3ed03652 testClass = SysUserControllerTest, testInstance = com.wt.common.security.controller.SysUserControllerTest@62e93c3a, testMethod = update@SysUserControllerTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@173797f0 testClass = SysUserControllerTest, locations = '{classpath:spring.xml, classpath:spring-mybatis.xml, classpath:spring-redis.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[org.springframework.test.context.web.socket.MockServerContainerContextCustomizer@4efbca5a], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.test.context.web.WebDelegatingSmartContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true]].
2018-05-21 21:02:49,962  INFO TransactionContext:105 - Began transaction (1) for test context [DefaultTestContext@3ed03652 testClass = SysUserControllerTest, testInstance = com.wt.common.security.controller.SysUserControllerTest@6944e53e, testMethod = removeUser@SysUserControllerTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@173797f0 testClass = SysUserControllerTest, locations = '{classpath:spring.xml, classpath:spring-mybatis.xml, classpath:spring-redis.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[org.springframework.test.context.web.socket.MockServerContainerContextCustomizer@4efbca5a], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.test.context.web.WebDelegatingSmartContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true]]; transaction manager [org.springframework.jdbc.datasource.DataSourceTransactionManager@3c35c345]; rollback [true]
2018-05-21 21:02:49,962  INFO MockServletContext:438 - Initializing Spring FrameworkServlet ''
2018-05-21 21:02:49,963  INFO TestDispatcherServlet:494 - FrameworkServlet '': initialization started
2018-05-21 21:02:49,965  INFO TestDispatcherServlet:513 - FrameworkServlet '': initialization completed in 2 ms
2018-05-21 21:02:49,978  INFO LoginInterceptor:63 - ⭐️{User-Agent:[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36],Protocol:[HTTP/1.1],Remote Addr:[127.0.0.1],Method:[DELETE],uri:[/sysUser/6057e4e4da6542f2bc32de5a43096dcd],Cookie:[null],operator:[ceshi],parameters:[["6057e4e4da6542f2bc32de5a43096dcd"]]}⭐️

MockHttpServletRequest:
      HTTP Method = DELETE
      Request URI = /sysUser/6057e4e4da6542f2bc32de5a43096dcd
       Parameters = {}
          Headers = {Content-Type=[application/json;charset=UTF-8], Accept=[application/json;charset=UTF-8], User-Agent=[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36], X-Requested-With=[XMLHttpRequest]}
             Body = null
    Session Attrs = {LOGINUSER=com.wt.common.security.model.SysUser@1e469dfd}

Handler:
             Type = com.wt.common.security.controller.SysUserController
           Method = public com.wt.common.core.result.HttpResultEntity<?> com.wt.common.security.controller.SysUserController.removeUser(java.lang.String)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {Content-Type=[application/json;charset=UTF-8]}
     Content type = application/json;charset=UTF-8
             Body = {"errorCode":"0","message":"SUCCESS","result":null}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
2018-05-21 21:02:49,994  INFO TransactionContext:137 - Rolled back transaction for test context [DefaultTestContext@3ed03652 testClass = SysUserControllerTest, testInstance = com.wt.common.security.controller.SysUserControllerTest@6944e53e, testMethod = removeUser@SysUserControllerTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@173797f0 testClass = SysUserControllerTest, locations = '{classpath:spring.xml, classpath:spring-mybatis.xml, classpath:spring-redis.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[org.springframework.test.context.web.socket.MockServerContainerContextCustomizer@4efbca5a], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.test.context.web.WebDelegatingSmartContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true]].
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 4.295 sec
2018-05-21 21:02:49,998  INFO GenericWebApplicationContext:989 - Closing org.springframework.web.context.support.GenericWebApplicationContext@59af0466: startup date [Mon May 21 21:02:47 CST 2018]; root of context hierarchy
2018-05-21 21:02:50,007  INFO DruidDataSource:1823 - {dataSource-1} closed

Results :

Tests run: 5, Failures: 0, Errors: 0, Skipped: 1

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 6.527 s
[INFO] Finished at: 2018-05-21T21:02:50+08:00
[INFO] Final Memory: 16M/307M
[INFO] ------------------------------------------------------------------------

Process finished with exit code 0
View Code