-
Notifications
You must be signed in to change notification settings - Fork 9
Home
zhugongrui edited this page Jul 13, 2016
·
7 revisions
jutf主要解决两个问题
- 数据准备:单测方法开始前执行指定的sql文件,单测方法执行完成后回滚数据
- 恢复污染对象:恢复spring容器中被mockito污染的对象。mockito参考:https://github.com/mockito/mockito
修改pom文件,增加如下jar包依赖
<dependency>
<groupId>com.github.knightliao.test</groupId>
<artifactId>jutf</artifactId>
<version>1.0.1-SNAPSHOT</version>
<scope>test</scope>
</dependency>
- 项目中常用数据库是mysql,但单测中不推荐使用mysql作为测试数据源;因为当多人同时运行单元测试时,有可能产生死锁,导致单测失败
- 推荐使用内存数据库H2,这样一来单测运行绝对隔离,不会互相干扰。缺点是:H2只支持标准sql
- mysql建表schema转H2,可使用这个工具:https://github.com/knightliao/mysql2h2-converter
如果使用H2作为单测数据源,增加如下依赖:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.3.174</version>
<scope>test</scope>
</dependency>
H2数据源配置:其中schema.sql就是通过mysql2h2-converter工具根据mysql库生成的
<!-- start h2数据源 -->
<bean id="h2_dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${h2.driver_class_name}" />
<property name="url" value="${h2.datasource_location}" />
<property name="username" value="{h2.username}" />
<property name="password" value="{h2.password}" />
</bean>
<jdbc:initialize-database data-source="h2_dataSource">
<jdbc:script encoding="utf-8" location="classpath:sql/base/schema/schema.sql"/>
</jdbc:initialize-database>
<!-- end h2数据源 -->
<!-- start mysql数据源 -->
<bean id="mysql_dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<!-- 驱动类 -->
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${car.jdbc.url}" />
<property name="username" value="${car.jdbc.username}" />
<property name="password" value="${car.jdbc.password}" />
<!-- Connection Pooling DBCP -->
<property name="validationQuery" value="SELECT 1" />
<property name="initialSize" value="${dbcp.initialSize}" />
<property name="maxActive" value="${dbcp.maxActive}" />
<property name="maxIdle" value="${dbcp.maxIdle}" />
<property name="maxWait" value="${dbcp.maxWait}" />
<property name="poolPreparedStatements" value="${dbcp.poolPreparedStatements}" />
<property name="defaultAutoCommit" value="${dbcp.defaultAutoCommit}" />
</bean>
<!-- end mysql数据源 -->
<!-- 数据源 -->
<bean id="unitTestDataSource" class="com.github.knightliao.test.datasource.UnitTestDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="mysql" value-ref="mysql_dataSource" />
<entry key="h2" value-ref="h2_dataSource" />
</map>
</property>
</bean>
如果项目中使用kepler,可对远程主机的rpc服务进行mock,使得单测依赖尽可能少、只关心自身代码的业务逻辑。 RPC框架kepler:https://github.com/Kepler-Framework/Kepler-All
<bean id="demoRpcService" class="com.github.knightliao.test.mocks.MockUpBean">
<constructor-arg index="0"
value="com.my.test.rpc.service.DemoRpcService"/>
</bean>