单元测试的时候,繁琐的老是创建 持久工厂,简直受不了,于是乎,有了下面的它 ,
/**
*
* @author hesheng
* 本地测试基类,不用启动 服务器,
* 测试数据需要自己模拟
*/
public abstract class BaseTestCase {
protected EntityManagerFactory emf;
protected EntityManager entityManager;
protected static boolean isOpenDB = true;
public boolean isOpenDB() {
return isOpenDB;
}
public void setOpenDB(boolean isOpenDB) {
this.isOpenDB = isOpenDB;
}
@SuppressWarnings("unchecked")
public void beginTx() {
emf = Persistence.createEntityManagerFactory("UnitName");
entityManager = emf.createEntityManager();
System.out.println("em: " + entityManager);
entityManager.getTransaction().begin();
}
public abstract void test();
public void endTx() {
entityManager.getTransaction().commit();
entityManager.close();
emf.close();
}
public void runTest(){
if(isOpenDB){
beginTx();
}
test();
if(isOpenDB){
endTx();
}
}
}
具体实现:
public class UnitTest extends BaseTestCase {
@Override
public void test() {
//getLogResultSet();
super.setOpenDB(false); //测试 JPQL 拼写是否正确的时候,不需连接数据库,因此可以,关闭创建连接,减少时间浪费
testSql(null,null);
}
public String testSql(String logTimeStart,String logTimeEnd){
String ql = "select m.pageName,count(m) as count from table m ";
int count = 0;
if (logTimeStart != null){
//ql = ql + " and";
count ++;
ql = ql + " where m.createDate >= ?" + count;
}
if (logTimeEnd != null){
ql = ql + " and";
count ++;
ql = ql + " m.createDate <= ?" + count;
}
ql = ql + " group by m.pageName";
System.out.println("ql: "+ql);
return ql;
}
public static void main(String[] args) {
new PageViewCountActionTest().runTest(); // 启动运行类,in eclipse "run as Application"
}