在二十三天中我们介绍了使用maven来下载工程的依赖库文件,用ant来进行war包的建立。今天我们在这个基础上将使用junit+dbunit来进行带有单元测试报告的框架的架构。
目标:
---------------------------------------------------------
One or more tests failed, check the report for detail...
---------------------------------------------------------
package org.sky.ssh.ut;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "/spring/appconfig/applicationContext.xml", "/org/sky/ssh/ut/ds/datasource.xml",
"/spring/hibernate/hibernate.xml" })
public class BaseSpringContextCommon {
}
我们先来书写一个单元测试类吧
package org.sky.ssh.ut;
import static org.junit.Assert.assertEquals;
import javax.annotation.Resource;
import org.junit.Test;
import org.sky.ssh.dao.LoginDAO;
import org.springframework.test.annotation.Rollback;
public class TestLoginDAO extends BaseSpringContextCommon {
@Resource
private LoginDAO loginDAO;
@Test
@Rollback(false)
public void testLoginDAO() throws Exception {
String loginId = "alpha";
String loginPwd = "aaaaaa";
long answer = loginDAO.validLogin(loginId, loginPwd);
assertEquals(1, answer);
}
}
运行方法为:
在eclipse打开该类的情况下右键->run as Junit Test
然后选junit4来运行,运行后直接出错抛出:
Class not found org.sky.ssh.ut.TestLoginDAO
java.lang.ClassNotFoundException: org.sky.ssh.ut.TestLoginDAO
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.loadClass(RemoteTestRunner.java:693)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.loadClasses(RemoteTestRunner.java:429)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:452)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
这样一个错误,为什么?
其原因在于我们的工程是在eclipse里使用的m2 eclipse这个插件生成的,因此在做单元测试时由于我们的unit test的类是放在test/main/java这个目录下,而这个目录是我们手工建的,因此eclipse不知道这个目录的对应的编译输出的class的目录了.
没关系,按照下面的方法:
右键->选择run as->run configuration,打开如下的设置
选择classpath这个选项栏
我们有了junit为什么还要引入一个dbunit呢?这不是多此一举吗?
试想一下下列场景:
我们开发时连的是开发用的数据库,一张表里有一堆的数据,有些数据不是自己的插的是其它的开发人员插的,那么我想要测试一个dao或者是service方法,获得一个List,然后判断这个List里的值是否为我想要的时候,有可能会碰到下属这样的情况:
运行我的service或者dao方法得到一个list,该list含有6个值,但正好在运行时另一个开发人员因为测试需要往数据库里又插了一些值,导致我的测试方法失败,对不对,这种情况是有可能的。
怎么办呢?比较好的做法是我们需要准备一份自己的业务数据即prepare data,因为是我们自己准备的数据数据,因此它在经过这个方法运行后得到的值,这个得到的值是要经过一系列的业务逻辑的是吧?因此这个得到的值即:expected data是可以被精确预料的。
因此,我们拿着这个expected data与运行了我们的业务方法后得到的结果进行比对,如果比对结果一致,则一定是测试成功,否则失败,对吧?
这就是我们常说的,测试用数据需要是一份干净的数据。
那么为了保持我们的数据干净,我们在测试前清空我们的业务表,插入数据,运行测试地,比对结果,删除数据(也可以不删除,因为每次运行时都会清空相关的业务表),这也就是为什么我们事先要专门搞一个数据库或者是数据库实例,在运行单元测试时我们的数据库连接需要指向到这个单元测试专用的数据库的原因了,见下面的测试流程表:
有了DbUnit,它就可以帮助我们封装:
package org.sky.ssh.ut.util;
import org.dom4j.Element;
import org.dom4j.VisitorSupport;
import java.util.*;
public class CleanTableXmlAdapter extends VisitorSupport {
private ArrayList tableList = new ArrayList();
public CleanTableXmlAdapter() {
}
public void visit(Element node) {
try {
if ((node.getName().toLowerCase()).equals("table")) {
TableBean tBean = new TableBean();
tBean.setTableName(node.getText());
tableList.add(tBean);
}
} catch (Exception e) {
}
}
public ArrayList getTablesList() {
if (tableList == null || tableList.size() < 1) {
return null;
} else {
return tableList;
}
}
}
package org.sky.ssh.ut.util;
import java.io.*;
public class TableBean implements Serializable{
private String tableName = "";
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
}
package org.sky.ssh.ut.util;
import java.util.*;
import java.io.*;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.VisitorSupport;
import org.dom4j.io.SAXReader;
import org.springframework.core.io.ClassPathResource;
public class XmlUtil {
public ArrayList getCleanTables(String xmlFile) {
ArrayList tablesList = new ArrayList();
try {
SAXReader reader = new SAXReader();
File file = new File(xmlFile);
Document doc = reader.read(file);
CleanTableXmlAdapter xmlAdapter = new CleanTableXmlAdapter();
doc.accept(xmlAdapter);
tablesList = xmlAdapter.getTablesList();
return tablesList;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
t_student
package org.sky.ssh.ut;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.DefaultDataSet;
import org.dbunit.dataset.DefaultTable;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.dbunit.ext.mysql.MySqlDataTypeFactory;
import org.dbunit.operation.DatabaseOperation;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.sky.ssh.service.StudentService;
import org.sky.ssh.ut.util.TableBean;
import org.sky.ssh.ut.util.XmlUtil;
import org.sky.ssh.vo.StudentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.test.annotation.Rollback;
public class TestStudentService extends BaseSpringContextCommon {
private final static String INSERT_TBL = "org/sky/ssh/ut/xmldata/student/test_insert_table.xml";
private final static String DEL_TBL = "org/sky/ssh/ut/xmldata/student/test_del_table.xml";
@Autowired
private DataSource dataSource;
@Resource
private StudentService stdService;
@SuppressWarnings("deprecation")
@Before
public void setUp() throws Exception {
IDatabaseConnection connection = null;
try {
connection = new DatabaseConnection(DataSourceUtils.getConnection(dataSource));
DatabaseConfig config = connection.getConfig();
config.setProperty("http://www.dbunit.org/properties/datatypeFactory", new MySqlDataTypeFactory());
//trunkTables(connection);
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL url = classLoader.getResource(INSERT_TBL);
if (url == null) {
classLoader = ClassLoader.getSystemClassLoader();
url = classLoader.getResource(INSERT_TBL);
}
IDataSet dateSetInsert = new FlatXmlDataSetBuilder().build(new FileInputStream(url.getFile()));
DatabaseOperation.CLEAN_INSERT.execute(connection, dateSetInsert);
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
if (connection != null) {
connection.close();
}
}
}
@After
public void tearDown() throws Exception {
IDatabaseConnection connection = null;
try {
connection = new DatabaseConnection(DataSourceUtils.getConnection(dataSource));
DatabaseConfig config = connection.getConfig();
config.setProperty("http://www.dbunit.org/properties/datatypeFactory", new MySqlDataTypeFactory());
//trunkTables(connection);
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
if (connection != null) {
connection.close();
}
}
}
private void trunkTables(IDatabaseConnection connection) throws Exception {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL url = classLoader.getResource(DEL_TBL);
if (url == null) {
classLoader = ClassLoader.getSystemClassLoader();
url = classLoader.getResource(DEL_TBL);
}
XmlUtil xmlUtil = new XmlUtil();
List tablesList = xmlUtil.getCleanTables(url.getFile());
Iterator it = tablesList.iterator();
while (it.hasNext()) {
TableBean tBean = (TableBean) it.next();
IDataSet dataSetDel = new DefaultDataSet(new DefaultTable(tBean.getTableName()));
DatabaseOperation.DELETE_ALL.execute(connection, dataSetDel);
}
}
@Test
@Rollback(false)
public void testGetAllStudent() throws Exception {
List stdList = new ArrayList();
stdList = stdService.getAllStudent();
assertEquals(5, stdList.size());
}
}
# ant
appName=myssh2
webAppName=myssh2
webAppQAName=myssh2-UT
local.dir=C:/eclipsespace/${appName}
src.dir=${local.dir}/src/main/java
test.src.dir=${local.dir}/test/main/java
dist.dir=${local.dir}/dist
report.dir=${local.dir}/report
webroot.dir=${local.dir}/src/main/webapp
lib.dir=${local.dir}/lib
ext-lib.dir=${local.dir}/ext-lib
classes.dir=${webroot.dir}/WEB-INF/classes
resources.dir=${local.dir}/src/main/resources
---------------------------------------------------------
One or more tests failed, check the report for detail...
---------------------------------------------------------