我正在寻找为典型的DAO方法(按用户名查找用户等)构建单元测试的信息,我发现了几个使用mock的示例,例如:http://www.christophbrill.de/de_DE/unit-testing-with-junit-and-mockito/
@Test
public void testComeGetSome() {
// Mock the EntityManager to return our dummy element
Some dummy = new Some();
EntityManager em = Mockito.mock(EntityManager.class);
Mockito.when(em.find(Some.class, 1234)).thenReturn(dummy);
// Mock the SomeDao to use our EntityManager
SomeDao someDao = Mockito.mock(SomeDao.class);
Mockito.when(someDao.comeGetSome(1234)).thenCallRealMethod();
Mockito.when(someDao.getEntityManager()).thenReturn(em);
// Perform the actual test
Assert.assertSame(dummy, someDao.comeGetSome(1234));
Assert.assertNull(someDao.comeGetSome(4321));
}
在Lasse Koskela的书中也有一个类似的例子,使用EasyMock代替Mockito。
问题是:我们在这些例子中真正测试的是什么?我们基本上通过模拟告诉查询应该返回什么对象,然后断言它实际上返回了我们让它返回的对象。我们不测试查询是否正确,或者它是否返回不同的对象或根本没有对象(甚至多个对象)。当对象在数据库中不存在时,我们无法测试它是否返回null。这条线
Assert.assertNull(someDao.comeGetSome(4321));
工作是因为该参数没有脚本交互,而不是因为对象不存在。
看起来我们只是在测试方法是否调用了正确的方法和对象(em.find)。
单元测试的意义是什么?在Java中有什么好的框架可以快速设置内存数据库并使用它执行测试吗?
你的怀疑确实有道理。实际上,在大多数情况下不需要用单元测试来测试DAO,因为单元测试处理的是一层,而DAO是与数据库层协同工作的。
这篇文章解释了这个想法:http://www.petrikainulainen.net/programming/testing/writing-tests-for-data-access-code-unit-tests-are-waste/
因此我们应该用集成测试来测试DAO和数据库层。集成测试同时考虑DAO和数据库层。
这篇文章将为你提供Spring + Hibernate的例子:https://dzone.com/articles/easy-integration-testing
它看起来更像是服务测试,而不是真正的DAO测试。例如,我使用dbunit
来测试我的DAO层。
例如,我有Author
表,有2个字段:id
和name
。我正在创建一个像
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<AUTHOR AUTHOR_ID="1" NAME="FirstAuthor"/>
...
<AUTHOR AUTHOR_ID="10" NAME="TenthAuthor"/>
</dataset>
然后在我的测试类中使用Mockito
测试我的DAO方法,比如
@Test
@DatabaseSetup(value = "/dao/author/author-data.xml")
public void testFindAll() {
List<Author> authorList = this.authorDAO.findAll();
assertEquals(10, authorList.size());
}