尝试对使用 Hibernate 进行数据库查询但无法创建会话的类进行单元测试
我正在尝试为使用 Hibernate 执行数据库查询的类实现 JUnit 测试。当我创建被测试的类时,我可以通过执行以下操作来通过工厂访问会话:
InitialContext context = new InitialContext();
sessionFactory = (SessionFactory) context.lookup(hibernateContext);
当我将其部署到 JBoss 5.1 时,效果很好。我正在尝试弄清楚如何让它与我的 JUnit 测试一起工作。我不断收到异常,指出我“需要在环境或系统属性中指定类名,或者作为小程序参数,或者在应用程序资源文件中指定类名:java.naming.factory.initial”。我到处搜索,但找不到任何关于我具体需要做什么才能让它发挥作用的信息。我没有使用 Spring 或任何框架,只是使用普通的旧 Java 和 JUnit。
I am trying to implement JUnit tests for a class that performs DB queries using Hibernate. When I create the class under test, I get access to the session through the factory by doing the following:
InitialContext context = new InitialContext();
sessionFactory = (SessionFactory) context.lookup(hibernateContext);
This works fine when I deploy this to JBoss 5.1. I am trying to figure out how to get this to work with my JUnit test. I keep getting an exception stating that I "Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial". I've searched high and low but haven't been able to find any information about what specifically I need to do to get this to work. I am not using Spring or any frameworks, just plain old Java and JUnit.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在单元测试环境中,您很可能不想从 JNDI 获取会话工厂(您不想启动 JBoss 进行单元测试),我的建议是使用一个好的旧
HibernateUtil
帮助程序类。下面是一个非常基本的示例:为了以防万一,caveat emptor 示例应用程序(本机版本)有一个更高级的版本,可以从静态变量或 JNDI 查找中获取全局 SessionFactory (因此您可以在容器内部和外部使用相同的代码)。
就我个人而言,我在很长一段时间里都使用过 Cameron McKenzie 的 时间。
然后,从
SessionFactory
获取Session
并为单元测试中的每个方法开始/提交/回滚事务。In a unit test context, you very likely don't want to get your session factory from JNDI (you don't want to start JBoss for unit tests) and my recommendation would be to use a good old
HibernateUtil
helper class. Below, a very basic example:Just in case, the caveat emptor sample application (the native version) has a a more advanced version that can get a global SessionFactory either from a static variable or a JNDI lookup (so you can use the same code in and outside the container).
Personally, I've used the one from Cameron McKenzie during a long time.
Then, get a
Session
from theSessionFactory
and begin/commit/rollback a transaction for each method in your unit test.看看 http://static.springsource.org/spring/docs/3.0.0.RC3/javadoc-api/org/springframework/mock/jndi/SimpleNamingContextBuilder.html
Have a look at http://static.springsource.org/spring/docs/3.0.0.RC3/javadoc-api/org/springframework/mock/jndi/SimpleNamingContextBuilder.html