具體的代碼參考鏈接: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框架的使用