基于h2和Spring测试的几个要点

基于h2和Spring测试的几个要点

========H2====
下载H2的zip包,解压,运行bin下的批处理文件,自动打开连接页面,注意选择Embedded、Server ,两者的连接方式是不一样的(弄了半天发现写不进数据,就是因为这点)。

h2 的几种Database URLs

Database URLs

Embedded
jdbc:h2:~/test 'test' in the user home directory 在我的文档下用户下建立数据文件
jdbc:h2:/data/test 'test' in the directory /data
jdbc:h2:test in the current(!) working directory


In-Memory
jdbc:h2:mem:test multiple connections in one process
jdbc:h2:mem: unnamed private; one connection


Server Mode
jdbc:h2:tcp://localhost/~/test user home dir 在我的文档下用户下建立数据文件,只有运行时存在
jdbc:h2:tcp://localhost//data/test absolute dir
Server start:java -cp *.jar org.h2.tools.Server

Settings
jdbc:h2:..;MODE=MySQL compatibility (or HSQLDB,...)
jdbc:h2:..;TRACE_LEVEL_FILE=3 log to *.trace.db

=========spring 测试========

测试数据库免不了增删改查,这样会改动数据库,在这里用Spring测试框架可以避免数据库改动。
参考http://zmfkplj.iteye.com/blog/370921

我写了个简单的测试例子 ,用的是springSide,其实也可以继承AbstractTransactionalJUnit4SpringContextTests
如:
public class ArticleDaoTest extends AbstractTransactionalJUnit4SpringContextTests{

package com.xx.unit.dao.account;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springside.modules.test.spring.SpringTxTestCase;

import com.xx.dao.account.ArticleDao;
import com.xx.entity.account.Article;

@ContextConfiguration(locations = {"/applicationContext-test.xml"})
public class ArticleDaoTest extends SpringTxTestCase{

@Autowired
private ArticleDao ad;

@Test
// @Rollback(false)//写入数据库不回滚
// @Repeat(10)//重复执行10次
public void daoTest(){
//保存文章
Article a = new Article();
a.setSubject("dowload");
a.setContent("kkkktest");
ad.save(a);
ad.flush();

//查找文章
a = ad.get(1L);
assertEquals("dowload",a.getSubject());

//删除文章

ad.delete(1L);
ad.flush();
Article a1 = ad.findUniqueBy("id", 1L);
assertNull(a1);
}
}



这样就省得每个类都加入下面类似代码了
public class UserDaoTest {
private ApplicationContext ctx;
@Before
public void before()throws Exception{
ctx = new ClassPathXmlApplicationContext("beans.xml");
}

@After
public void tearDown() throws Exception {
System.out.println("end");
}

@Test
public void saveTest(){
UserDao userDao = (UserDao)ctx.getBean("userDao");
userDao.save();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值