junit+mock+spring-test构建后台单元测试
from:从0开始,构建前后端分离应用
1. 一些基本概念
1.1 为什么要进行单元测试?我自己的理解是
1.2 什么是Mock
1.3对后台的测试粒度
采用junit+mock+spring-test进行的测试,是对SpringMvc的一个完整的测试,测试过程会包含DispatcherServlet、数据绑定、拦截器等环节,甚至连视图渲染都可以进行测试。是对后台请求的一个完整测试。并且不需要启动tomcat服务器
2. 添加依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${version.junit}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${version.spring}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>${version.mockito}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>${version.hamcrest}</version>
<scope>test</scope>
</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>
3. 一些注意事项
1、在编写测试用例的时候,往往要编写基类。@RunWith这个注解是不能写在基类中的,否则基类也会被当成测试用例而执行。而基类中是没有任何测试方法的,这时候junit会报错
有一个变通的方法,@RunWith注解仍然写在基类上,但是为基类增加@Ignore注解,这样在执行Test的时候,就不执行基类了
2、测试代码放在哪个路径下,这里一定注意,卡了我很久。我最开始的时候写在了/project/test/路径下,结果就是无论怎么执行test命令,测试用例都不行,提示“no tests to run”
正确的方式应该是将测试代码放在/project/src/test/java/路径下
定义基类的目的,就是将公共的代码抽象到更高的层次。这里包括注解和代码
4、测试过程的环节
准备测试环境,包括Spring上下文的配置、测试数据、mockMvc初始化、请求头信息的设置、返回预期的设置等
通过MockMvc执行请求
使用断言对结果 进行验证
4. 具体实现
BaseTest.java:
1、定义通用注解,由于代码中的注解都是可以继承的,因此完全可以抽象到基类中,避免其他的测试用例重复的声明这些注解
注意,@Ignore是必须要添加的,否则Maven的surefire插件也会将基类当成一个测试用例来运行,而基类中是没有任何测试方法的,结果就是报错
2、buildResultActions方法中,定义所有请求的通用设置,header信息,及请求结果的期望值,还有对测试过程的打印。其中就使用了hamcrest判断结果中是否包含SUCCESS信息,如果不包含就证明出错了。另外还定义了Session信息,否则后台会因为session中没有用户信息,而将请求拦截住。
package com.wt.test.common; import com.google.gson.Gson;
import com.wt.common.security.handler.HttpSessionHandler;
import com.wt.common.security.model.SysUser;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
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.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
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; /**
* @ProjectName: syInfo
* @Package: com.wt.com.wt.test
* @Description:
* @Author: lichking2017@aliyun.com
* @CreateDate: 2018/5/19 下午5:04
* @Version: v1.0
*/ @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring.xml", "classpath:spring-mybatis.xml", "classpath:spring-redis.xml"})
@WebAppConfiguration
@Transactional
@Ignore
public class BaseTest {
Logger logger = LoggerFactory.getLogger(BaseTest.class); @Autowired
WebApplicationContext webApplicationContext; protected MockMvc mockMvc; protected SysUser loginUser; protected Gson gson = new Gson(); @Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
loginUser = this.createLoginUser();
} /**
* 通用设置
* @param mhsrb
* @return
*/
protected ResultActions buildResultActions(MockHttpServletRequestBuilder mhsrb) {
mhsrb.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
.accept(MediaType.APPLICATION_JSON_UTF8_VALUE)
.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")
.header("X-Requested-With", "XMLHttpRequest")
.sessionAttr(HttpSessionHandler.Items.LOGINUSER.name(), loginUser);
try {
return mockMvc
.perform(mhsrb)
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(MockMvcResultMatchers.content().string(Matchers.containsString("SUCCESS")))
.andDo(MockMvcResultHandlers.print());
} catch (Exception e) {
logger.error("请求通用设置出错",e);
}
return null;
} private SysUser createLoginUser() {
SysUser sysUser = new SysUser();
sysUser.setUserId("0279c9d48c774b5b825dfb6d1058a816");
sysUser.setAccount("admin");
sysUser.setUserName("系统超级管理员");
return sysUser;
} @After
public void tearDown() throws Exception { } }
测试用例:SysUserControllerTest
1、对于新增用的测试,主要是比对新增前后的表的记录数
2、对更新用户的测试,主要是比对更新后的用户名与要更新的名称是否一致
3、删除用户,也是比对删除前后的记录实现的
package com.wt.common.security.controller; import com.wt.common.security.model.SysUser;
import com.wt.common.security.service.SysUserService;
import com.wt.test.common.BaseTest;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; /**
* @ProjectName: syInfo
* @Package: com.wt.common.security.controller
* @Description:
* @Author: lichking2017@aliyun.com
* @CreateDate: 2018/5/19 下午5:01
* @Version: v1.0
*/
public class SysUserControllerTest extends BaseTest { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); @Autowired
private SysUserService sysUserService; private SysUser sysUser; @Override
public void setUp() throws Exception {
super.setUp();
sysUser = this.createSysUser();
} @Test
public void findSysUserByUserId() throws Exception {
} @Test
@Rollback
public void create() throws Exception {
List<SysUser> sysUsers = sysUserService.selectAll();
int beforCount = sysUsers.size() + 1;
super.buildResultActions(MockMvcRequestBuilders
.post("/sysUser/create")
.content(gson.toJson(sysUser)));
List<SysUser> sysUserList = sysUserService.selectAll();
int afterCount = sysUserList.size();
Assert.assertTrue(beforCount == afterCount);
} @Test
public void removeUser() throws Exception {
List<SysUser> beforeUsers = sysUserService.selectAll();
int beforCount = beforeUsers.size();
String userId = "";
for (SysUser sysUser : beforeUsers) {
if ("admin".equals(sysUser.getAccount())) {
continue;
}
userId = sysUser.getUserId();
break;
} super.buildResultActions(MockMvcRequestBuilders
.delete("/sysUser/{userId}", userId)).andReturn(); List<SysUser> afterUsers = sysUserService.selectAll();
int afterCount = afterUsers.size()+1;
assertThat(beforCount, Matchers.equalTo(afterCount));
} @Test
public void update() throws Exception {
try {
List<SysUser> beforeUsers = sysUserService.selectAll();
SysUser forUpdate = new SysUser();
String targetName = simpleDateFormat.format(new Date()); for (SysUser sysUser : beforeUsers) {
if ("admin".equals(sysUser.getAccount())) {
continue;
}
forUpdate = sysUser;
break;
}
String userId = forUpdate.getUserId();
forUpdate.setUserName(targetName);
super.buildResultActions(MockMvcRequestBuilders.put("/sysUser").content(gson.toJson(forUpdate)));
SysUser updatedUser = sysUserService.findById(userId,SysUser.class);
Assert.assertTrue(targetName.equals(updatedUser.getUserName()));
} catch (Exception e) {
e.printStackTrace();
}
} private SysUser createSysUser() {
SysUser sysUser = new SysUser();
sysUser.setUserName("测试数据" + simpleDateFormat.format(new Date()));
sysUser.setPassword("ceshi");
sysUser.setAccount(simpleDateFormat.format(new Date()));
sysUser.setInUse(true);
sysUser.setMail("test@aliyun.com");
return sysUser;
}
}
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
junit+mock+spring-test构建后台单元测试的更多相关文章
- Java单元测试(Junit+Mock+代码覆盖率)---------转
Java单元测试(Junit+Mock+代码覆盖率) 原文见此处 单元测试是编写测试代码,用来检测特定的.明确的.细颗粒的功能.单元测试并不一定保证程序功能是正确的,更不保证整体业务是准备的. 单元测 ...
- Junit+Mock单元测试
项目用的是maven,所需jar包在pom.xml文件里面配置,单元测试要用的jar具体如下: <dependency> <groupId>junit</groupId& ...
- Spring+Junit+Mock测试web项目,即Controller
准备:Maven依赖 <!-- Spring和MVC的包这里不列出来了,webmvc,aspects,orm,其他maven会自动导 --> <dependency> < ...
- [spring源码学习]单元测试演化
1.使用main方法 最早的测试方法一般是在类中增加main方法,然后在main方法中增加对每个方法的测试代码,如果要测其中一个,就屏蔽掉其他的测试代码,执行后,根据log的打印来判断测试是否成功 2 ...
- Mock&Spring集成
Mock&Spring集成 常规Mock单元测试 请参考上一篇文档Mock mock框架的功能性对比 http://jmockit.github.io/MockingToolkitCompar ...
- 真正意义上的spring环境中的单元测试方案spring-test与mokito完美结合
真正意义上的spring环境中的单元测试方案spring-test与mokito完美结合 博客分类: java 测试 单元测试SpringCC++C# 一.要解决的问题: spring环境中 ...
- Spring Boot中使用 Spring Security 构建权限系统
Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架.它提供了一组可以在Spring应用上下文中配置的Bean,为应用系统提供声明式的安全 ...
- 【Spring】构建Spring Web应用
前言 学习了Spring的注解.AOP后,接着学习Spring Web,对于Web应用开发,Spring提供了Web框架. Web应用 Spring MVC初探 MVC为(Model-View-Con ...
- 【转】Spring Boot 构建应用——快速构建 Spring Boot 应用
Spring Boot 简化了 Spring 应用开发,不需要配置就能运行 Spring 应用,Spring Boot 的自动配置是通过 Spring 4.x 的条件注解 @Conditional 来 ...
随机推荐
- winform编程设定listview选中行
在做项目中,需要用到listview显示数据.同时,项目要求,通过检索用户输入的数据,程序通过搜索,确定数据所在的行并通过程序设定为选中状态并高亮显示.同时,正常响应鼠标单击响应的效果,单击时,程序设 ...
- myBatis源码之Configuration
Configuration类主要是用来存储对mybatis的配置文件及mapper文件解析后的数据,Configuration对象会贯穿整个myabtis的执行流程,为mybatis的执行过程提供必要 ...
- 面试之路(8)-BAT面试题之数组和链表的区别
两种数据结构都是线性表,在排序和查找等算法中都有广泛的应用 各自的特点: 数组: 数组是将元素在内存中连续存放,由于每个元素占用内存相同,可以通过下标迅速访问数组中任何元素.但是如果要在数组中增加一个 ...
- The 14th tip of DB Query Analyzer
The 14th tip of DB Query Analyzer Ma Genfeng (Guangdong Unitoll Services incorporated, Guangzhou 5 ...
- solr研磨之facet
作者:战斗民族就是干 转载请注明地址:http://www.cnblogs.com/prayers/p/8822417.html Facet 开门见山,facet解决的就是筛选,我是把它理解为一种聚合 ...
- 记一次erlang语言bug导致rabbitmq的队列没有消费者的问题
公司开发和测试环境采用的erlang版本是19.0.3,rabbitmq版本为3.6.10.集群条件下稳定使用了近一年时间,没什么问题. 为了保持和线下一致,线上生产环境采用了相同的版本,运行几个月后 ...
- SPRING事务的属性有哪些?其中,事务隔离级别有哪几种?什么情况需要使用这几种事务隔离级别?
Spring 声明式事务,propagation属性列表 PROPAGATION_REQUIRED:支持当前事务,如果当前没有事务,就新建一个事务.这是最常见的选择. PROPAGATION_SU ...
- 关于Linux和Unix的分析
Linux操作系统即linux. Linux是一套免费使用和自由传播的类Unix操作系统,是一个基于POSIX和UNIX的多用户.多任务.支持多线程和多CPU的操作系统.它能运行主要的UNIX工具软 ...
- MySQL运维工具
Mysql运维过程中设计的各类工具以及各个场景的的命令行的分类.大体总结如下的xmind图片(.xmind附件 加 Q1123654342). 大体上分为: 实例管理工具.高可用工具.慢日志查询工具. ...
- 影响Sql server性能的因素
目前本人在看<SQL Server性能调优实战> ,以下内容是本人看书笔记 数据库性能取决于各方面综合因素: 硬件,操作系统,软件 硬件:内存,CPU,磁盘 当服务器的物理内存不足时,会产 ...