Java Web并发单元测试(1)

简介:
大的 web项目开发和运行环境都在服务器容器中进行为主,包括调试过程,也都是单例进过Web触发进行 测试。在Web项目中设计使用Spring、hibernate、JBPM工作流、ehcache各种框架或组件。这些东西在一起配置好一个有效的、覆盖所有环境的 单元测试用例也比较复杂。所有配置好一个可用有效的单元测试环境十分必要。并且面对单元测试对并发要求的不支持,还得加入必要的并发测试组件,满足测试全面系统 白盒测试要求。
   这里总结几种有效的配置单元测试方式:
  1、直接使用Junit4组件,进行简单单元测试,在setUp()中初始化各种测试环境如下:
@Override
protected void setUp() throws Exception {
super.setUp();
String[] paths = { "classpath:applicationContext.xml" };
ApplicationContext ctx = new ClassPathXmlApplicationContext(paths);
SpringContextListener.setApplicationContext(ctx);
// ############模拟servlet容器启动,手动更改配置文件路径
Constant.CURRENT_PROJECT_PATH = "src/";
// ############直接容器中获取bean
userManager = (UserManager) ctx.getBean("userManager");
userService = (UserService) ctx.getBean("userService");
}
   2、使用Sprint-test.jar框架,支持事务可注解方式启动的单元测试:
  @RunWith(SpringJUnit4ClassRunner.class)
  @ContextConfiguration(locations = "classpath:applicationContext.xml")
  @TransactionConfiguration(transactionManager="transactionManager",defaultRollback=false) //true将会回滚所有操作,默认没有该注解为回滚
  public class JBPMProcessTest2 extends  AbstractTransactionalJUnit4SpringContextTests{
  以上都只能暂时支持简单功能的单元测试。但是要测试并发和压力等。需要加入一个常用的框架,支持在单元测试中注入多线程和并发。
  具体参见:http://blog.csdn.net/zhangyaoming2004/article/details/7619489 下面附有Jar包下载 http://yunpan.cn/QUtVay66VnU4T
  我们具体使用的功能不是很多,这些并发测试可以嵌入到上面两种单元测试方式中:如下:
/**
*
*/
package com.dtsz.model.service.test;
import net.sourceforge.groboutils.junit.v1.TestRunnable;
import com.dtsz.model.entity.report.common.InvokeSource;
import com.dtsz.model.service.ExcelReportLogicService;
import com.dtsz.model.service.TaskLogicService;
import com.dtsz.model.util.ExcelReportUtil;
import com.dtsz.view.vo.authenticator.UserVO;
import com.dtsz.view.vo.webservice.ExcelReportResult;
/**
* 模拟插件端数据上报的并发操作测试
*
* @author xiaoli
*
*/
public class CreateMulltiTaskReportGroboThread extends TestRunnable {
TaskLogicService taskLogicService;
ExcelReportLogicService excelReportLogicService;
private String reportMap;
private UserVO user;
private InvokeSource invokeSource;
private String bbq;
public CreateMulltiTaskReportGroboThread(String reportMap, UserVO user, InvokeSource invokeSource,String bbq) {
super();
this.reportMap = reportMap;
this.user = user;
this.invokeSource = invokeSource;
this.bbq = bbq;
init();
}
public void init() {
taskLogicService = (TaskLogicService)ExcelReportUtil.getBean("taskLogicService");
excelReportLogicService = (ExcelReportLogicService)ExcelReportUtil.getBean("excelReportLogicService");
}
/*
* (non-Javadoc)
*
* @see net.sourceforge.groboutils.junit.v1.TestRunnable#runTest()
*/
@Override
public void runTest() throws Throwable {
// TODO Auto-generated method stub
// ########################模拟当前任务该报表期任务上报
//保存数据
ExcelReportResult result = taskLogicService.reportData(reportMap, user, invokeSource);
excelReportLogicService.saveData(result);
System.out.println("报表期为:"+this.bbq+"已上报");
}
}

 单元测试并发:
/**
*
*/
package com.dtsz.model.service.test;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
import net.sourceforge.groboutils.junit.v1.MultiThreadedTestRunner;
import net.sourceforge.groboutils.junit.v1.TestRunnable;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.dtsz.model.entity.authenticator.User;
import com.dtsz.model.entity.report.common.InvokeSource;
import com.dtsz.model.service.authenticator.UserManager;
import com.dtsz.model.service.authenticator.UserService;
import com.dtsz.model.service.exception.BaseAppException;
import com.dtsz.model.util.BeanUtil2;
import com.dtsz.model.util.Constant;
import com.dtsz.model.util.Encryption;
import com.dtsz.view.util.SpringContextListener;
import com.dtsz.view.vo.authenticator.UserVO;
/**
* 模拟数据上报,这里的初始化数据根据插件端传入数据组合来的,当前只有根据报表期生成初始化数据
*
* @author xiaoli
*
*/
public class CreateMultiTaskReportTest3 extends TestCase {
private UserManager userManager;
private UserService userService;
@Override
protected void setUp() throws Exception {
super.setUp();
String[] paths = { "classpath:applicationContext.xml" };
ApplicationContext ctx = new ClassPathXmlApplicationContext(paths);
SpringContextListener.setApplicationContext(ctx);
// ############模拟servlet容器启动,手动更改配置文件路径
Constant.CURRENT_PROJECT_PATH = "src/";
// ############直接容器中获取bean
userManager = (UserManager) ctx.getBean("userManager");
userService = (UserService) ctx.getBean("userService");
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
@Test
public void test(){
// ###########自动生成报表期串集合
List<String> bbqs = new ArrayList<String>();
UnitTestUtils.imitateCreateMultiBbq(bbqs, 2, "2048", "5");
// 创建线程
TestRunnable[] tr = new TestRunnable[bbqs.size()];
int processCount = 0;
// ##########对这些数据进行填报
for (String bbq : bbqs) {
// 模拟上报数据
String reportMap = "{taskID:\"402880ee425a92f501425aa75ad50002\",bbq_:\""
+ bbq
+ "\""
+ ",bbhid:\"402855b942099b1b014209b1177e03f5\",approvalFlag:2,reportFlag:False,auditFlag:False,sheetMap:"
+ "[{id:\"402880ee425a92f501425aa75ad60004\",sheetType:\"BASIC\",values:{}}]}";
// 模拟上报的user
UserVO user = null;
try {
user = checkUser("xl1", "1");
} catch (BaseAppException e) {
e.printStackTrace();
} // 模拟插件端checkUser
String sessionInfo = "{institutionname:\"南昌分行\",institutioncode:\"A01NC\",username:\"肖力1"
+ "1\",usercode:\"xl1\",rolecode:\"null\",bbhId:\"402855b942099b1b014209b1177e03f5\",bbhcode:\"B01b\",btype:\"BASIC\",taskid:\"402880ee425a92f501425a"
+ "a75ad50002\",bbhname:\"基层财务b\",bbq:\"" + bbq
+ "\",frequency:\"MONTH\",SESSIONDIMENSION:{}}";
try {
userService.updateSession(sessionInfo, user);
} catch (BaseAppException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} // 模拟插件端updateSession
// 初始化上报方式
InvokeSource invokeSource = InvokeSource.WSCALL;
CreateMulltiTaskReportGroboThread reportThread = new CreateMulltiTaskReportGroboThread(reportMap,user, invokeSource,bbq);
tr[processCount] = reportThread;
processCount++;
}
System.out.println("#######################################计时开始########################");
long startTime = System.currentTimeMillis();
// 生成测试线程运行器
MultiThreadedTestRunner mttr = new MultiThreadedTestRunner(tr);
// 运行测试线程
try {
mttr.runTestRunnables();
} catch (Throwable e) {
e.printStackTrace();
}
System.out.println("#######################一共耗时:"
+ String.valueOf((System.currentTimeMillis() - startTime) / 1000) + "秒");
}
/**
* xl1 1
* */
public UserVO checkUser(String userid,
String password) throws BaseAppException {
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("UserName", userid);
paramMap.put("Password", password);
List<User> users = userManager.findByCodeCache(userid);
List<User> needUsers = new ArrayList<User>();
if (users != null && users.size() > 0) {
for (User user : users) {
if (user.getState() && user.getCode().equals(userid)
&& user.getPassword().equals(Encryption.encryption(password))) {
needUsers.add(user);
}
}
}
// 通过验证
if (needUsers != null && needUsers.size() > 0) {
User user = needUsers.get(0);
// 获取用户权限,并存放于session中
// UserVO userVO = userManager.getUserPermission(user.getId());
String ipAddress = "0.0.0.0";
UserVO userVO = new UserVO();
BeanUtil2.copyProperties(user, userVO);
userVO.setIpAddress(ipAddress);
return userVO; // 通过验证
} else {
return null;
}
}
}
  真实环境并发和压力测试不仅仅是在多个线程同时启动在测,还可能是增量式压力测试。这些还是要封装好和处理好。

最新内容请见作者的GitHub页:http://qaseven.github.io/

相关文章
|
2月前
|
安全 Java API
Java Web 在线商城项目最新技术实操指南帮助开发者高效完成商城项目开发
本项目基于Spring Boot 3.2与Vue 3构建现代化在线商城,涵盖技术选型、核心功能实现、安全控制与容器化部署,助开发者掌握最新Java Web全栈开发实践。
366 1
|
2月前
|
存储 前端开发 Java
【JAVA】Java 项目实战之 Java Web 在线商城项目开发实战指南
本文介绍基于Java Web的在线商城技术方案与实现,涵盖三层架构设计、MySQL数据库建模及核心功能开发。通过Spring MVC + MyBatis + Thymeleaf实现商品展示、购物车等模块,提供完整代码示例,助力掌握Java Web项目实战技能。(238字)
325 0
|
3月前
|
算法 IDE Java
Java 项目实战之实际代码实现与测试调试全过程详解
本文详细讲解了Java项目的实战开发流程,涵盖项目创建、代码实现(如计算器与汉诺塔问题)、单元测试(使用JUnit)及调试技巧(如断点调试与异常排查),帮助开发者掌握从编码到测试调试的完整技能,提升Java开发实战能力。
433 0
|
1月前
|
Java 大数据 Go
从混沌到秩序:Java共享内存模型如何通过显式约束驯服并发?
并发编程旨在混乱中建立秩序。本文对比Java共享内存模型与Golang消息传递模型,剖析显式同步与隐式因果的哲学差异,揭示happens-before等机制如何保障内存可见性与数据一致性,展现两大范式的深层分野。(238字)
63 4
|
1月前
|
缓存 安全 Java
如何理解Java中的并发?
Java并发指多任务交替执行,提升资源利用率与响应速度。通过线程实现,涉及线程安全、可见性、原子性等问题,需用synchronized、volatile、线程池及并发工具类解决,是高并发系统开发的关键基础。(238字)
198 4
|
3月前
|
JavaScript Java 微服务
现代化 Java Web 在线商城项目技术方案与实战开发流程及核心功能实现详解
本项目基于Spring Boot 3与Vue 3构建现代化在线商城系统,采用微服务架构,整合Spring Cloud、Redis、MySQL等技术,涵盖用户认证、商品管理、购物车功能,并支持Docker容器化部署与Kubernetes编排。提供完整CI/CD流程,助力高效开发与扩展。
483 64
|
3月前
|
前端开发 Java 数据库
Java 项目实战从入门到精通 :Java Web 在线商城项目开发指南
本文介绍了一个基于Java Web的在线商城项目,涵盖技术方案与应用实例。项目采用Spring、Spring MVC和MyBatis框架,结合MySQL数据库,实现商品展示、购物车、用户注册登录等核心功能。通过Spring Boot快速搭建项目结构,使用JPA进行数据持久化,并通过Thymeleaf模板展示页面。项目结构清晰,适合Java Web初学者学习与拓展。
306 1
|
4月前
|
SQL 缓存 安全
深度理解 Java 内存模型:从并发基石到实践应用
本文深入解析 Java 内存模型(JMM),涵盖其在并发编程中的核心作用与实践应用。内容包括 JMM 解决的可见性、原子性和有序性问题,线程与内存的交互机制,volatile、synchronized 和 happens-before 等关键机制的使用,以及在单例模式、线程通信等场景中的实战案例。同时,还介绍了常见并发 Bug 的排查与解决方案,帮助开发者写出高效、线程安全的 Java 程序。
236 0
|
4月前
|
安全 Java 测试技术
Java 项目实战中现代技术栈下代码实现与测试调试的完整流程
本文介绍基于Java 17和Spring技术栈的现代化项目开发实践。项目采用Gradle构建工具,实现模块化DDD分层架构,结合Spring WebFlux开发响应式API,并应用Record、Sealed Class等新特性。测试策略涵盖JUnit单元测试和Testcontainers集成测试,通过JFR和OpenTelemetry实现性能监控。部署阶段采用Docker容器化和Kubernetes编排,同时展示异步处理和反应式编程的性能优化。整套方案体现了现代Java开发的最佳实践,包括代码实现、测试调试
208 0
|
4月前
|
人工智能 Java 测试技术
Java or Python?测试开发工程师如何选择合适的编程语言?
测试工程师如何选择编程语言?Java 还是 Python?多位资深专家分享建议:Python 入门简单、开发效率高,适合新手及自动化测试;Java 生态成熟,适合大型项目和平台开发。建议结合公司技术栈、个人基础及发展方向选择。长远来看,两者兼通更佳,同时关注 Go 等新兴语言。快速学习与实践才是关键。