【发布时间】:2018-10-05 06:02:38
【问题描述】:
我没有使用任何框架,只使用 maven war 模块,想使用 Juit 4 + Powermockito 测试 DAO 层(第一次)。
我的想法是当我调用 CustomerDao 来测试 createCustomer。该方法的第一个语句如下:
Session session = HibernateManager.getInstance().getSessionFactory().openSession();
我想模拟这个调用,以便我可以使用以下代码提供我在测试类中构造的会话对象:
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.modules.junit4.PowerMockRunner;
import com.dao.CustomerDao;
@RunWith(PowerMockRunner.class)
public class CustomerDaoTest {
private SessionFactory sessionFactory;
@Mock
CustomerDao customer=new CustomerDao();
@Before
public void setup() {
sessionFactory = createSessionFactory();
}
@Test
public void CustomerCreateAndDeleteTest() throws Exception {
// Want to mock here
int id=customer.createCustomer("Indian Customer", "India", "xyz@pk.com",
"234567890", "AB");
Assert.assertEquals(1, id);
}
private SessionFactory createSessionFactory() {
Configuration configuration = new Configuration().configure("hibernate.cfg.h2.xml");// Using H2 for testing only
sessionFactory = configuration.buildSessionFactory();
return sessionFactory;
}
}
问题是:
- 运行测试类时出现错误:
org.hibernate.internal.util.config.ConfigurationException:无法 在 RESOURCE 中的行号 -1 和列 -1 处执行解组 休眠.cfg.h2.xml。消息:意外元素 (uri:"http://www.hibernate.org/xsd/orm/cfg", 本地:“休眠配置”)。预期的元素是
但是如果我删除注释@RunWith(PowerMockRunner.class)
那么我没有收到此错误。
- 如何模拟 createCustomer() 方法内部的方法调用,如下所示:
Session session = HibernateManager.getInstance().getSessionFactory().openSession();
请指导我如何编写单元测试用例来测试可以使用不同 hibernate.cfg.xml 文件的 DAO 层。
【问题讨论】:
-
模拟一个会话来测试你的 DAO 基本上是没有用的。您的 DAO 的职责是使用查询从数据库中获取数据。所以基本上,您需要检查的是查询是否正确并从数据库返回正确的值。模拟会话只会检查您是否正在执行查询。您仍然不知道查询是否正确,以及它是否返回正确的数据。不要使用模拟来测试你的 DAO。相反,在测试开始时用测试数据填充您的数据库,调用您的 DAO,并检查它是否返回了正确的数据。
-
模拟你正在测试的 DAO 更不正确:你甚至不会执行任何一行代码,而是测试 Mockito 是否正常工作。
-
感谢 Prashant 的回复,但在我的情况下,有用于保存对象的标准方法,如 session.save() 我想通过在测试用例。
-
这正是您不应该模拟您的 DAO 或 Hibernate 会话的原因。如果你模拟它,它的所有方法都会被模拟,并且什么也不做。所以你不能检查他们是否正确地完成了他们的工作。我的名字是 JB Nizet,不是 Prashant。
-
啊!对不起,JB 非常感谢您的回复。你能告诉我如果我想测试我的凝乳操作那么应该是什么方法。因为如果我不模拟会话,那么如果我从测试类调用该方法,它将进入我不想要的数据库,这就是为什么我想在内存数据库 H2 中使用,如果我请纠正我我错了
标签: java spring hibernate junit4 powermockito