1. 程式人生 > >對Spring整合Mybatis進行測試

對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的方法.