对Spring整合Mybatis进行测试


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

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations ={"classpath:/configuration/spring/beans.xml"})

@Transactional

@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)

public class TestModule{

    @Test

    public void testAdd() {

        try {

        dao.save(module);

        }catch(Exception e) {

            e.printStackTrace();

        }

        }

}

这里需要对



defaultRollback = true

说明: true  测试数据不会污染数据库 : 会真正添加到数据库当中

当然这里不污染数据库只是在表中看不到数据, 但是如果你设置的主键是自动增长的话, 那么可以很明显得看出,虽然数据回滚了,但是当你尝试不回滚新增数据到数据库的时候, 会发现ID不是连续的.所以并不是真正意义上的无污染

当然,这种方式也有他的好处,比单纯JUNIT要省去@before ,@after的方法.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值