java SSM框架单元测试最佳实战代码
具体的代码参考链接:https://pan.baidu.com/s/1e9UTyidi4OMBwYydhwH-0g 密码:rmvs
本教程采用的是对单元测试的dao层、service层、control层进行单元测试
其中采用的测试框架可以是junit,也可以是testNG
对应dao层的测试采用的框架是TestNg+dbunit+spring-test-dbunit框架
对应的service层的测试采用的框架是powermock+dbunit+spring-test框架
对应的control层采用的测试框架是mockmvc+dbunit+spring-test框架
项目采用的是maven进行管理:其中数据库使用的是mysql
对应的数据库文件如下:
对于的sql文件内容如下:
ssm_crud.sql
/* Navicat MySQL Data Transfer Source Server : 本地电脑2 Source Server Version : 50527 Source Host : localhost:3306 Source Database : ssm_crud Target Server Type : MYSQL Target Server Version : 50527 File Encoding : 65001 Date: 2018-07-06 16:56:08 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for `tbl_dept` -- ---------------------------- DROP TABLE IF EXISTS `tbl_dept`; CREATE TABLE `tbl_dept` ( `dept_id` int(1) NOT NULL AUTO_INCREMENT, `dept_name` varchar(255) DEFAULT NULL, PRIMARY KEY (`dept_id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of tbl_dept -- ---------------------------- INSERT INTO `tbl_dept` VALUES ('1', '研发部'); INSERT INTO `tbl_dept` VALUES ('2', '测试部'); -- ---------------------------- -- Table structure for `tbl_emp` -- ---------------------------- DROP TABLE IF EXISTS `tbl_emp`; CREATE TABLE `tbl_emp` ( `emp_id` int(11) NOT NULL AUTO_INCREMENT, `emp_name` varchar(255) DEFAULT NULL, `gender` varchar(1) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, `d_id` int(11) NOT NULL, PRIMARY KEY (`emp_id`), KEY `d-Id` (`d_id`), CONSTRAINT `d-Id` FOREIGN KEY (`d_id`) REFERENCES `tbl_dept` (`dept_id`) ) ENGINE=InnoDB AUTO_INCREMENT=7889 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of tbl_emp -- ---------------------------- INSERT INTO `tbl_emp` VALUES ('10', 'admin10', 'M', '1878899@qq.com', '1'); INSERT INTO `tbl_emp` VALUES ('12', 'weqwe', 'M', 'wssfesfdfd', '2'); INSERT INTO `tbl_emp` VALUES ('200', 'kebi', null, '899090e@qq.com', '1'); INSERT INTO `tbl_emp` VALUES ('233', '33', '3', '3', '2'); INSERT INTO `tbl_emp` VALUES ('7888', 'kebi', 'M', '899090e@qq.com', '1');
项目对于的工程如下:就是一个maven整合ssm,采用springmvc+spring+mybatis的一个整合,视频可以参考尚硅谷ssm高级整合视频教程
使用到的整合的配置文件如下所示:
我们来看下具体的每个配置文件,因为使用的maven管理,在pom文件中对jar包进行依赖管理
<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>com.atguigu</groupId> <artifactId>ssm-crud</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <!--引入项目依赖的jar包 --> <!-- SpringMVC、Spring --> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependencies> <!--引入pageHelper分页插件 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.0.0</version> </dependency> <!-- MBG --> <!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core --> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.5</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.7.RELEASE</version> </dependency> <!-- 返回json字符串的支持 --> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.8</version> </dependency> <!--JSR303数据校验支持;tomcat7及以上的服务器, tomcat7以下的服务器:el表达式。额外给服务器的lib包中替换新的标准的el --> <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.4.1.Final</version> </dependency> <!-- Spring-Jdbc --> <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.7.RELEASE</version> </dependency> <!--Spring-test --> <!-- https://mvnrepository.com/artifact/org.springframework/spring-test --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.7.RELEASE</version> </dependency> <!-- Spring面向切面编程 --> <!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.3.7.RELEASE</version> </dependency> <!--MyBatis --> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.2</version> </dependency> <!-- MyBatis整合Spring的适配包 --> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!-- 数据库连接池、驱动 --> <!-- https://mvnrepository.com/artifact/c3p0/c3p0 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.41</version> </dependency> <!-- (jstl,servlet-api,junit) --> <!-- https://mvnrepository.com/artifact/jstl/jstl --> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>jstl-api</artifactId> <version>1.2</version> <exclusions> <exclusion> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> </exclusion> <exclusion> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> <!-- junit --> <!-- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!-- springmvc测试框架所需用的的包 --> <dependency> <groupId>com.jayway.jsonpath</groupId> <artifactId>json-path-assert</artifactId> <version>0.8.1</version> </dependency> <dependency> <groupId>com.jayway.jsonpath</groupId> <artifactId>json-path</artifactId> <version>0.8.0</version> </dependency> <!-- json --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.3</version> </dependency> <!-- dbutil测试工具的引入依赖 --> <dependency> <groupId>com.github.springtestdbunit</groupId> <artifactId>spring-test-dbunit</artifactId> <version>1.2.0</version> </dependency> <dependency> <groupId>org.dbunit</groupId> <artifactId>dbunit</artifactId> <version>2.5.0</version> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.8</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>1.10.19 </version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-mockito</artifactId> <version>1.6.5</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-testng</artifactId> <version>1.6.5</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-core</artifactId> <version>1.6.5</version> <scope>test</scope> </dependency> </dependencies> </project>
mybatis-config.xml
<?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> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <!-- 给下面com.atguigu.crud.bean启用别名,默认就是类名的第一个字母小写Employee对应的别名就是employee --> <typeAliases> <package name="com.atguigu.crud.bean"/> </typeAliases> <!-- 需要注意的是分页插件必须放在<typeAliases>的后面 --> <plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <!--分页参数合理化 --> <property name="reasonable" value="true"/> </plugin> </plugins> </configuration>
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd"> <!-- 配置扫描控制器 ,springmvc值扫描controler,其他的对象都让spring去管理,这里use-default-filters="false"要设置成false--> <context:component-scan base-package="com.atguigu" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 配置视图解析器 --> <!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 配置视图解析器的前缀和后缀 --> <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 配置允许访问静态资源文件 --> <mvc:default-servlet-handler/> <!-- 支持springmvc的更加高级的东西 --> <mvc:annotation-driven></mvc:annotation-driven> </beans>
dbconfig.properties
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm_crud
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=123456
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!-- Spring配置文件的核心点(数据源、与mybatis的整合,事务控制) --> <!-- 配置c3p0数据源 --> <!-- 引入外部的数据库配置文件 --> <context:property-placeholder location="classpath:dbconfig.properties"/> <bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="user" value="${jdbc.user}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!-- 配置spring的IOC,但是不能扫描springmvc的controller,spring 扫描service dao utils的bean controller由springmvc去扫描 --> <context:component-scan base-package="com.atguigu"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--================== 配置和MyBatis的整合=============== --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 指定mybatis全局配置文件的位置 --> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <!-- 数据源就是上面配置的c3p0数据源 --> <property name="dataSource" ref="pooledDataSource"></property> <!-- 指定mybatis,mapper文件的位置 ,扫描mapper文件夹下面的所有配置文件--> <property name="mapperLocations" value="classpath:mapper/*.xml"></property> </bean> <!-- 配置一个可以执行批量的sqlSession --> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg> <constructor-arg name="executorType" value="BATCH"></constructor-arg> </bean> <!-- 通过自动扫描简化mapper的配置 前面的章节可以看到,我们的dao需要一个一个的配置在配置文件中, 如果有很多个dao的话配置文件就会非常大,这样管理起来就会比较痛苦。 幸好mybatis团队也意识到了这点, 他们利用spring提供的自动扫描功能封装了一个自动扫描dao的工具类,这样我们就可以使用这个功能简化配置: --> <!-- 配置扫描器,将mybatis接口的实现加入到ioc容器中 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--扫描所有dao接口的实现,加入到ioc容器中 --> <property name="basePackage" value="com.atguigu.crud.dao"></property> </bean> <!-- ===============事务控制的配置 ================--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--控制住数据源 --> <property name="dataSource" ref="pooledDataSource"></property> </bean> <!--开启基于注解的事务,使用xml配置形式的事务(必要主要的都是使用配置式) --> <!--配置事务增强,事务如何切入 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 所有方法都是事务方法 --> <tx:method name="*"/> <!--以get开始的所有方法 --> <tx:method name="get*" read-only="true"/> </tx:attributes> </tx:advice> <!-- 配置哪些类的哪些方法使用事务(配置事务边界,配置Pointcut) --> <aop:config> <aop:pointcut id="allManagerMethod" expression="execution(* com.weiyuan.test.service.*.*(..))"/> <aop:advisor pointcut-ref="allManagerMethod" advice-ref="txAdvice"/> </aop:config> <!-- Spring配置文件的核心点(数据源、与mybatis的整合,事务控制) --> </beans>
mapper下是对应生成的mybatis的映射接口文件
DepartmentMapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.atguigu.crud.dao.DepartmentMapper"> <resultMap id="BaseResultMap" type="com.atguigu.crud.bean.Department"> <id column="dept_id" jdbcType="INTEGER" property="deptId" /> <result column="dept_name" jdbcType="VARCHAR" property="deptName" /> </resultMap> <sql id="Example_Where_Clause"> <where> <foreach collection="oredCriteria" item="criteria" separator="or"> <if test="criteria.valid"> <trim prefix="(" prefixOverrides="and" suffix=")"> <foreach collection="criteria.criteria" item="criterion"> <choose> <when test="criterion.noValue"> and ${criterion.condition} </when> <when test="criterion.singleValue"> and ${criterion.condition} #{criterion.value} </when> <when test="criterion.betweenValue"> and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} </when> <when test="criterion.listValue"> and ${criterion.condition} <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=","> #{listItem} </foreach> </when> </choose> </foreach> </trim> </if> </foreach> </where> </sql> <sql id="Update_By_Example_Where_Clause"> <where> <foreach collection="example.oredCriteria" item="criteria" separator="or"> <if test="criteria.valid"> <trim prefix="(" prefixOverrides="and" suffix=")"> <foreach collection="criteria.criteria" item="criterion"> <choose> <when test="criterion.noValue"> and ${criterion.condition} </when> <when test="criterion.singleValue"> and ${criterion.condition} #{criterion.value} </when> <when test="criterion.betweenValue"> and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} </when> <when test="criterion.listValue"> and ${criterion.condition} <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=","> #{listItem} </foreach> </when> </choose> </foreach> </trim> </if> </foreach> </where> </sql> <sql id="Base_Column_List"> dept_id, dept_name </sql> <select id="selectByExample" parameterType="com.atguigu.crud.bean.DepartmentExample" resultMap="BaseResultMap"> select <if test="distinct"> distinct </if> <include refid="Base_Column_List" /> from tbl_dept <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> <if test="orderByClause != null"> order by ${orderByClause} </if> </select> <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from tbl_dept where dept_id = #{deptId,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from tbl_dept where dept_id = #{deptId,jdbcType=INTEGER} </delete> <delete id="deleteByExample" parameterType="com.atguigu.crud.bean.DepartmentExample"> delete from tbl_dept <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> </delete> <insert id="insert" parameterType="com.atguigu.crud.bean.Department"> insert into tbl_dept (dept_id, dept_name) values (#{deptId,jdbcType=INTEGER}, #{deptName,jdbcType=VARCHAR}) </insert> <insert id="insertSelective" parameterType="com.atguigu.crud.bean.Department"> insert into tbl_dept <trim prefix="(" suffix=")" suffixOverrides=","> <if test="deptId != null"> dept_id, </if> <if test="deptName != null"> dept_name, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="deptId != null"> #{deptId,jdbcType=INTEGER}, </if> <if test="deptName != null"> #{deptName,jdbcType=VARCHAR}, </if> </trim> </insert> <select id="countByExample" parameterType="com.atguigu.crud.bean.DepartmentExample" resultType="java.lang.Long"> select count(*) from tbl_dept <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> </select> <update id="updateByExampleSelective" parameterType="map"> update tbl_dept <set> <if test="record.deptId != null"> dept_id = #{record.deptId,jdbcType=INTEGER}, </if> <if test="record.deptName != null"> dept_name = #{record.deptName,jdbcType=VARCHAR}, </if> </set> <if test="_parameter != null"> <include refid="Update_By_Example_Where_Clause" /> </if> </update> <update id="updateByExample" parameterType="map"> update tbl_dept set dept_id = #{record.deptId,jdbcType=INTEGER}, dept_name = #{record.deptName,jdbcType=VARCHAR} <if test="_parameter != null"> <include refid="Update_By_Example_Where_Clause" /> </if> </update> <update id="updateByPrimaryKeySelective" parameterType="com.atguigu.crud.bean.Department"> update tbl_dept <set> <if test="deptName != null"> dept_name = #{deptName,jdbcType=VARCHAR}, </if> </set> where dept_id = #{deptId,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.atguigu.crud.bean.Department"> update tbl_dept set dept_name = #{deptName,jdbcType=VARCHAR} where dept_id = #{deptId,jdbcType=INTEGER} </update> </mapper>
EmployeeMapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.atguigu.crud.dao.EmployeeMapper"> <resultMap id="BaseResultMap" type="com.atguigu.crud.bean.Employee"> <id column="emp_id" jdbcType="INTEGER" property="empId" /> <result column="emp_name" jdbcType="VARCHAR" property="empName" /> <result column="gender" jdbcType="CHAR" property="gender" /> <result column="email" jdbcType="VARCHAR" property="email" /> <result column="d_id" jdbcType="INTEGER" property="dId" /> </resultMap> <resultMap type="com.atguigu.crud.bean.Employee" id="WithDeptResultMap"> <id column="emp_id" jdbcType="INTEGER" property="empId" /> <result column="emp_name" jdbcType="VARCHAR" property="empName" /> <result column="gender" jdbcType="CHAR" property="gender" /> <result column="email" jdbcType="VARCHAR" property="email" /> <result column="d_id" jdbcType="INTEGER" property="dId" /> <!-- 指定联合查询出的部门字段的封装 --> <association property="department" javaType="com.atguigu.crud.bean.Department"> <id column="dept_id" property="deptId"/> <result column="dept_name" property="deptName"/> </association> </resultMap> <sql id="Example_Where_Clause"> <where> <foreach collection="oredCriteria" item="criteria" separator="or"> <if test="criteria.valid"> <trim prefix="(" prefixOverrides="and" suffix=")"> <foreach collection="criteria.criteria" item="criterion"> <choose> <when test="criterion.noValue"> and ${criterion.condition} </when> <when test="criterion.singleValue"> and ${criterion.condition} #{criterion.value} </when> <when test="criterion.betweenValue"> and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} </when> <when test="criterion.listValue"> and ${criterion.condition} <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=","> #{listItem} </foreach> </when> </choose> </foreach> </trim> </if> </foreach> </where> </sql> <sql id="Update_By_Example_Where_Clause"> <where> <foreach collection="example.oredCriteria" item="criteria" separator="or"> <if test="criteria.valid"> <trim prefix="(" prefixOverrides="and" suffix=")"> <foreach collection="criteria.criteria" item="criterion"> <choose> <when test="criterion.noValue"> and ${criterion.condition} </when> <when test="criterion.singleValue"> and ${criterion.condition} #{criterion.value} </when> <when test="criterion.betweenValue"> and ${criterion.condition} #{criterion.value} and #{criterion.secondValue} </when> <when test="criterion.listValue"> and ${criterion.condition} <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=","> #{listItem} </foreach> </when> </choose> </foreach> </trim> </if> </foreach> </where> </sql> <sql id="Base_Column_List"> emp_id, emp_name, gender, email, d_id </sql> <sql id="WithDept_Column_List"> e.emp_id, e.emp_name, e.gender, e.email, e.d_id,d.dept_id,d.dept_name </sql> <!-- List<Employee> selectByExampleWithDept(EmployeeExample example); Employee selectByPrimaryKeyWithDept(Integer empId); --> <!-- 查询员工同时带部门信息 --> <select id="selectByExampleWithDept" resultMap="WithDeptResultMap"> select <if test="distinct"> distinct </if> <include refid="WithDept_Column_List" /> FROM tbl_emp e left join tbl_dept d on e.`d_id`=d.`dept_id` <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> <if test="orderByClause != null"> order by ${orderByClause} </if> </select> <select id="selectByPrimaryKeyWithDept" resultMap="WithDeptResultMap"> select <include refid="WithDept_Column_List" /> FROM tbl_emp e left join tbl_dept d on e.`d_id`=d.`dept_id` where emp_id = #{empId,jdbcType=INTEGER} </select> <!-- 查询员工不带部门信息的 --> <select id="selectByExample" parameterType="com.atguigu.crud.bean.EmployeeExample" resultMap="BaseResultMap"> select <if test="distinct"> distinct </if> <include refid="Base_Column_List" /> from tbl_emp <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> <if test="orderByClause != null"> order by ${orderByClause} </if> </select> <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from tbl_emp where emp_id = #{empId,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from tbl_emp where emp_id = #{empId,jdbcType=INTEGER} </delete> <delete id="deleteByExample" parameterType="com.atguigu.crud.bean.EmployeeExample"> delete from tbl_emp <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> </delete> <insert id="insert" parameterType="com.atguigu.crud.bean.Employee"> insert into tbl_emp (emp_id, emp_name, gender, email, d_id) values (#{empId,jdbcType=INTEGER}, #{empName,jdbcType=VARCHAR}, #{gender,jdbcType=CHAR}, #{email,jdbcType=VARCHAR}, #{dId,jdbcType=INTEGER}) </insert> <insert id="insertSelective" parameterType="com.atguigu.crud.bean.Employee"> insert into tbl_emp <trim prefix="(" suffix=")" suffixOverrides=","> <if test="empId != null"> emp_id, </if> <if test="empName != null"> emp_name, </if> <if test="gender != null"> gender, </if> <if test="email != null"> email, </if> <if test="dId != null"> d_id, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="empId != null"> #{empId,jdbcType=INTEGER}, </if> <if test="empName != null"> #{empName,jdbcType=VARCHAR}, </if> <if test="gender != null"> #{gender,jdbcType=CHAR}, </if> <if test="email != null"> #{email,jdbcType=VARCHAR}, </if> <if test="dId != null"> #{dId,jdbcType=INTEGER}, </if> </trim> </insert> <select id="countByExample" parameterType="com.atguigu.crud.bean.EmployeeExample" resultType="java.lang.Long"> select count(*) from tbl_emp <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> </select> <update id="updateByExampleSelective" parameterType="map"> update tbl_emp <set> <if test="record.empId != null"> emp_id = #{record.empId,jdbcType=INTEGER}, </if> <if test="record.empName != null"> emp_name = #{record.empName,jdbcType=VARCHAR}, </if> <if test="record.gender != null"> gender = #{record.gender,jdbcType=CHAR}, </if> <if test="record.email != null"> email = #{record.email,jdbcType=VARCHAR}, </if> <if test="record.dId != null"> d_id = #{record.dId,jdbcType=INTEGER}, </if> </set> <if test="_parameter != null"> <include refid="Update_By_Example_Where_Clause" /> </if> </update> <update id="updateByExample" parameterType="map"> update tbl_emp set emp_id = #{record.empId,jdbcType=INTEGER}, emp_name = #{record.empName,jdbcType=VARCHAR}, gender = #{record.gender,jdbcType=CHAR}, email = #{record.email,jdbcType=VARCHAR}, d_id = #{record.dId,jdbcType=INTEGER} <if test="_parameter != null"> <include refid="Update_By_Example_Where_Clause" /> </if> </update> <update id="updateByPrimaryKeySelective" parameterType="com.atguigu.crud.bean.Employee"> update tbl_emp <set> <if test="empName != null"> emp_name = #{empName,jdbcType=VARCHAR}, </if> <if test="gender != null"> gender = #{gender,jdbcType=CHAR}, </if> <if test="email != null"> email = #{email,jdbcType=VARCHAR}, </if> <if test="dId != null"> d_id = #{dId,jdbcType=INTEGER}, </if> </set> where emp_id = #{empId,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.atguigu.crud.bean.Employee"> update tbl_emp set emp_name = #{empName,jdbcType=VARCHAR}, gender = #{gender,jdbcType=CHAR}, email = #{email,jdbcType=VARCHAR}, d_id = #{dId,jdbcType=INTEGER} where emp_id = #{empId,jdbcType=INTEGER} </update> </mapper>
现在我们把ssm的框架整合起来了,我们接下来查看如何进行单位
接下来我们来查看如何进行单元测试,首先对dao层进行单元测试
首先我们来查看dao层的代码
我们对EmployeeMapper进行单元测试
package com.atguigu.crud.dao; import com.atguigu.crud.bean.Employee; import com.atguigu.crud.bean.EmployeeExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface EmployeeMapper { long countByExample(EmployeeExample example); int deleteByExample(EmployeeExample example); int deleteByPrimaryKey(Integer empId); int insert(Employee record); int insertSelective(Employee record); List<Employee> selectByExample(EmployeeExample example); Employee selectByPrimaryKey(Integer empId); int updateByExampleSelective(@Param("record") Employee record, @Param("example") EmployeeExample example); int updateByExample(@Param("record") Employee record, @Param("example") EmployeeExample example); int updateByPrimaryKeySelective(Employee record); List<Employee> selectByExampleWithDept(EmployeeExample example); Employee selectByPrimaryKeyWithDept(Integer empId); int updateByPrimaryKey(Employee record); }
对于dao层的测试我们使用到了TestNg和dbunit已经spring-test-dbunit框架
eclipse本身不支持TestNg
我们需要下载Testng的插件不清楚的看自己的博客eclipse如何集成TestNg,这里下载TestNg的时候一定要注意TestNg的版本
org.testng.eclipse_6.8.6.20130607_0745,一定要使用6.8.6版本,但是自己下载的时候使用成了org.testng.eclipse_6.9.8.201510130443
高版本在运行testNg的时候出现了socket close的问题,使用了很久才解决
关于dbunit工具的时候请看视频孔浩老师junit单元测试dbunit工具的使用
在使用dbunit工具的使用使用到了一个
<!-- dbutil测试工具的引入依赖 -->
<dependency>
<groupId>com.github.springtestdbunit</groupId>
<artifactId>spring-test-dbunit</artifactId>
<version>1.2.0</version>
</dependency>
这个工具框架,很有用,我们来看具体的dao层的测试代码
DaoTestByTestNG.java
package com.atguigu.crud.test; import java.io.FileWriter; import java.util.List; import junit.framework.Assert; import org.dbunit.database.DatabaseConnection; import org.dbunit.database.IDatabaseConnection; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.xml.FlatXmlDataSet; import org.dbunit.dataset.xml.FlatXmlProducer; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.transaction.annotation.Transactional; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.xml.sax.InputSource; import com.atguigu.crud.bean.Employee; import com.atguigu.crud.bean.EmployeeExample; import com.atguigu.crud.bean.EmployeeExample.Criteria; import com.atguigu.crud.dao.DepartmentMapper; import com.atguigu.crud.dao.EmployeeMapper; import com.github.springtestdbunit.DbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.annotation.DatabaseTearDown; import com.github.springtestdbunit.annotation.DbUnitConfiguration; import com.github.springtestdbunit.annotation.ExpectedDatabase; import com.github.springtestdbunit.assertion.DatabaseAssertionMode; /** * 对dao进行单元测试的类 * classpath:/dbutils_xml/expect.xml * */ @SuppressWarnings("deprecation") @ContextConfiguration(locations = {"classpath:applicationContext.xml", "classpath:dispatcher-servlet.xml" }) //配置事务的回滚,对数据库的增删改都会回滚,便于测试用例的循环利用 @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true) @Transactional @TestExecutionListeners({DbUnitTestExecutionListener.class, DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class}) // 如果在Spring Test DbUnit中不配置其他的数据源默认使用Spring容器中id="dataSource"的数据源,Spring Test DbUnit支持配置多数据源。 @DbUnitConfiguration(databaseConnection="pooledDataSource") public class DaoTestByTestNG extends AbstractTestNGSpringContextTests { @Autowired private DepartmentMapper departmentMapper; @Autowired private EmployeeMapper employeeMapper; @Test @DatabaseSetup(type=DatabaseOperation.CLEAN_INSERT,value="classpath:/dbutils_xml/setup.xml")//setup阶段执行clean_insert操作,数据导入到数据库中,在测试之前执行 @ExpectedDatabase(assertionMode=DatabaseAssertionMode.NON_STRICT,value="classpath:/dbutils_xml/add_expect.xml")//将测试操作后的数据库数据与期望的xml数据进行比较是否相等,来判定测试是否通过,assertionMode设置比较的模式。跑完test后执行 @DatabaseTearDown(type=DatabaseOperation.CLEAN_INSERT,value="classpath:/dbutils_xml/setup.xml")//恢复数据库中的数据,测试之后执行。 public void testInsert() { System.out.println("insert"); Employee employee = new Employee(13, "kebi", "M", "kebi@qq.com", 2); employeeMapper.insert(employee); Employee employee2 = employeeMapper.selectByPrimaryKey(13); Assert.assertNotNull(employee2); Assert.assertEquals(employee.getEmpId(), employee2.getEmpId()); Assert.assertEquals(employee.getEmail(), employee2.getEmail()); Assert.assertEquals(employee.getEmpName(), employee2.getEmpName()); } /** * 修改联系人的操作 * */ @Test @DatabaseSetup(type=DatabaseOperation.CLEAN_INSERT,value="classpath:/dbutils_xml/setup.xml")//setup阶段执行clean_insert操作,数据导入到数据库中,在测试之前执行 @ExpectedDatabase(assertionMode=DatabaseAssertionMode.NON_STRICT,value="classpath:/dbutils_xml/update_expect.xml")//将测试操作后的数据库数据与期望的xml数据进行比较是否相等,来判定测试是否通过,assertionMode设置比较的模式。跑完test后执行 @DatabaseTearDown(type=DatabaseOperation.CLEAN_INSERT,value="classpath:/dbutils_xml/setup.xml")//恢复数据库中的数据,测试之后执行。 public void testUpdate() { System.out.println("update"); Employee employee = new Employee(12, "kebi", "M", "kebi@qq.com", 2); employeeMapper.updateByPrimaryKeySelective(employee); Employee employee2 = employeeMapper.selectByPrimaryKey(12); Assert.assertNotNull(employee2); Assert.assertEquals(employee.getEmpId(), employee2.getEmpId()); Assert.assertEquals(employee.getEmail(), employee2.getEmail()); Assert.assertEquals(employee.getEmpName(), employee2.getEmpName()); } /** * 删除联系人的操作 * */ /** * 修改联系人的操作 * */ @Test @DatabaseSetup(type=DatabaseOperation.CLEAN_INSERT,value="classpath:/dbutils_xml/setup.xml")//setup阶段执行clean_insert操作,数据导入到数据库中,在测试之前执行 @ExpectedDatabase(assertionMode=DatabaseAssertionMode.NON_STRICT,value="classpath:/dbutils_xml/delete_expect.xml")//将测试操作后的数据库数据与期望的xml数据进行比较是否相等,来判定测试是否通过,assertionMode设置比较的模式。跑完test后执行 @DatabaseTearDown(type=DatabaseOperation.CLEAN_INSERT,value="classpath:/dbutils_xml/delete_expect.xml")//恢复数据库中的数据,测试之后执行。 public void testDelete() { System.out.println("delete"); int deleteByPrimaryKey = employeeMapper.deleteByPrimaryKey(12); //此处通过update操作返回的受影响行数来断定update操作是否执行成功 } /** * 删除联系人的操作 * */ /** * 获得联系人的全部信息 * */ @Test @DatabaseSetup(type=DatabaseOperation.CLEAN_INSERT,value="classpath:/dbutils_xml/setup.xml")//setup阶段执行clean_insert操作,数据导入到数据库中,在测试之前执行 @ExpectedDatabase(assertionMode=DatabaseAssertionMode.NON_STRICT,value="classpath:/dbutils_xml/setup.xml")//将测试操作后的数据库数据与期望的xml数据进行比较是否相等,来判定测试是否通过,assertionMode设置比较的模式。跑完test后执行 @DatabaseTearDown(type=DatabaseOperation.CLEAN_INSERT,value="classpath:/dbutils_xml/setup.xml")//恢复数据库中的数据,测试之后执行。 public void testGetAllEmployees() { System.out.println("testGetAllEmployees"); EmployeeExample example = new EmployeeExample(); Criteria createCriteria = example.createCriteria(); List<Employee> list = employeeMapper.selectByExample(example); Assert.assertEquals(2, list.size()); Assert.assertEquals("admin10", list.get(0).getEmpName()); Assert.assertEquals("weqwe", list.get(1).getEmpName()); } //备份数据库文件 @BeforeClass public static void testBackup(){ try { System.out.println("@BeforeClass"); IDatabaseConnection con = new DatabaseConnection(DBUtils.getConnection()); IDataSet createDataSet = con.createDataSet(); FlatXmlDataSet.write(createDataSet, new FileWriter("d:/test22.xml")); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } //还原数据库文件 @AfterClass public static void testResume(){ try { System.out.println("@AfterClass"); IDatabaseConnection con = new DatabaseConnection(DBUtils.getConnection()); IDataSet dataSet = new FlatXmlDataSet(new FlatXmlProducer( new InputSource("d:/test22.xml"))); //清空数据库中的数据并插入xml中的数据 org.dbunit.operation.DatabaseOperation.CLEAN_INSERT.execute(con,dataSet); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
接下来重点对上面的代码几个关键点进行备注下:
第一需要:使用Spring-Test对Spring框架进行单元测试,需要引入下面的java包
<!--spring单元测试依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${springframework}</version>
<scope>test</scope>
</dependency>
第二:因为采用的TestNg测试框架,没有使用junit测试框架,所以在编写的单元测试类都需要继承AbstractTestNGSpringContextTests
如果使用的是junit的测试框架,直接使用注解@RunWith(SpringJUnit4ClassRunner.class)
第三:在运行单元测试框架的时候,使用首先dbunit备份数据库中的真实数据,然后在测试的过程中使用测试数据,最后单元测试完成之后再把保存的真实数据
还原到数据库中
//备份数据库文件 @BeforeClass public static void testBackup(){ try { System.out.println("@BeforeClass"); IDatabaseConnection con = new DatabaseConnection(DBUtils.getConnection()); IDataSet createDataSet = con.createDataSet(); FlatXmlDataSet.write(createDataSet, new FileWriter("d:/test22.xml")); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } //还原数据库文件 @AfterClass public static void testResume(){ try { System.out.println("@AfterClass"); IDatabaseConnection con = new DatabaseConnection(DBUtils.getConnection()); IDataSet dataSet = new FlatXmlDataSet(new FlatXmlProducer( new InputSource("d:/test22.xml"))); //清空数据库中的数据并插入xml中的数据 org.dbunit.operation.DatabaseOperation.CLEAN_INSERT.execute(con,dataSet); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
第四:spring-test-dbunit框架的使用
posted on 2018-07-06 17:41 luzhouxiaoshuai 阅读(4279) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!