关于springtestdbunit的基本使用,网上有很多例子和介绍,这里不再赘述,也可以参考
http://springtestdbunit.github.io/spring-test-dbunit/来学习springtestdbunit,
话不多说,先贴出使用springtestdbunit编写单元测试的代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:testContext.xml"})
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class,
DbUnitTestExecutionListener.class})
public class HelloTest {
@Test
@DatabaseSetup("classpath:full_flat.xml")
public void testSayHello() throws Exception {
Hello hello = new Hello();
hello.sayHello();
}
}
注意,这里没有指定任何的数据集类型,但是我们却给出了full_flat.xml作为DatabaseSetup,这是因为我们上篇文章中提到的,springtestdbunit默认使用的是FlatXmlDataSetLoader,下面贴出该类源码
public class FlatXmlDataSetLoader extends AbstractDataSetLoader {
@Override
protected IDataSet createDataSet(Resource resource) throws Exception {
FlatXmlDataSetBuilder builder = new FlatXmlDataSetBuilder();
InputStream inputStream = resource.getInputStream();
try {
return builder.build(inputStream);
} finally {
inputStream.close();
}
}
}
显然,默认使用了的FlatXml的方式去读取我们的资源文件,而我们这里需要用xml的方式解决上文提到的空数据问题,需要如何做呢,查看官方文档,找到如下一段话
By default DBUnit datasets are loaded from flat XML files. If you need to load data from another source you will need to write your own DataSet loader and configure your tests to use it. Custom loaders must implement the DataSetLoader interface and provide an implementation of the loadDataSet method. The AbstractDataSetLoader is also available and provides a convenient base class for most loaders.
大概意思是说DBUnit默认是使用flat XML的文件格式来加载数据集的,如果想要使用其他方式加载数据集,需要编写你自己的DataSet加载器,并且配置在你的单元测试中。
按照这个思路,我们编写一个自己的数据集加载器,XmlDataSetLoader
public class XmlDataSetLoader extends AbstractDataSetLoader {
@Override
protected IDataSet createDataSet(Resource resource) throws Exception {
InputStream inputStream = resource.getInputStream();
try {
return new XmlDataSet(inputStream);
} finally {
inputStream.close();
}
}
}
然后配置在单元测试中
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:testContext.xml"})
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class,
DbUnitTestExecutionListener.class})
@DbUnitConfiguration(dataSetLoader= XmlDataSetLoader.class)
public class HelloTest {
@Test
@DatabaseSetup("classpath:full_xml.xml")
public void testSayHello() throws Exception {
Hello hello = new Hello();
hello.sayHello();
}
}
注意加入的配置@DbUnitConfiguration,在这里指定了我们将要使用自行编写的XmlDataSetLoader作为数据集加载器。