1、创建测试表test_db:
2、创建一个JavaBean (TestTb)
/*** 测试JavaBean
*
*/
public class TestTb {
private Integer id;
private String name;
private Date birthday;
3、创建一个TestTbDao.java接口
/*** 测试接口
*
*/
public interface TestTbDao {
//保存数据
public void addTestTb(TestTb testTb);
}
4、 创建一个TestTbDao.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">
<!-- 正是Mybatis写Sql的标签 -->
<mapper namespace="test.core.dao.TestTbDao">
<!-- 添加保存测试数据 -->
<insert id="addTestTb" parameterType="TestTb">
insert into test_tb
(id,name,birthday)
values
(#{id},#{name},#{birthday})
</insert>
</mapper>
5、创建一个基于Spring的Junit单元测试(注解式)
/*** Junit单元测试是基于Spring 注解式
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:application-context.xml"})
public class SpringJunitTest {
}
/**
* Junit单元测试是基于Spring 注解式
*
*/
public class TestTestTb extends SpringJunitTest {
@Autowired
private TestTbDao testDao;
@Test
public void testAdd() throws Exception {
TestTb testTb = new TestTb();
testTb.setName("小明");
testDao.addTestTb(testTb);
}
}
测试事务:
@Service
@Transactional
public class TestTbServiceImpl implements TestTbService {
@Autowired
private TestTbDao testTbDao;
//添加
public void addTestTb(TestTb testTb){
testTbDao.addTestTb(testTb);
throw new RuntimeException();
}
}
对给予 spring的junit的一些说明:
4 5 6 7 8 9 10 11 12 13 14 |
|
这里需要对
|
|
说明: true 测试数据不会污染数据库 : 会真正添加到数据库当中
当然这里不污染数据库只是在表中看不到数据, 但是如果你设置的主键是自动增长的话, 那么可以很明显得看出,虽然数据回滚了,但是当你尝试不回滚新增数据到数据库的时候, 会发现ID不是连续的.所以并不是真正意义上的无污染
当然,这种方式也有他的好处,比单纯JUNIT要省去@before ,@after的方法.