您的位置:首页 > 其它

maven+hibernate使用Junit测试找不到hibernate.cfg.xml 的解决

2014-04-19 14:00 351 查看
使用了Junit去测试maven管理的项目,会出现找不到配置资源。而我的项目是用到hibernate的,又没有使用到Spring。所以出现下面的异常信息。
Initial SessionFactory creation failed.org.hibernate.HibernateException: /hibernate.cfg.xml not found。

原因:在maven项目中,hibernate.cfg.xml在src/resource包中,并不是在src目录下,尽管在web容器下面hibernate.cfg.xml会输出到WEB-INF/Class文件夹中去,但是junit是脱离web容器测试的。

百度谷歌找不到解决方法。又在csdn中的J2ee论坛下提问过,帖子地址如下:http://bbs.csdn.net/topics/390760743?page=1#post-397199290。

有几位热心的网友给了我一些建议,但是我自己觉得不是很满意,再次谷歌,翻了几页后,终于找到一个国外帖子,地址为http://www.shaunabram.com/hibernate-maven-unit-tests/

翻一下他的解决方法:

1) Copy the hibernate.cfg.xml file to

my-app/target/classes

复制hibernate.cfg到
/target/classes里面,不过他本人不推荐。

2) The next solution I found suggested moving the hibernate.cfg.xml to

my-app/src/main/resources

将 hibernate.cfg.xml
移动/src/main/resources目录下。这个其实我本人就是这么干的,但是依然会出现上面的异常。

3) The next and I think best solution was to create a new, duplicate hibernate.cfg.xml inside

my-app/src/test/resources

新建一个文件夹,路径为sre/texs/resoures。这个也是他本人推荐的。尝试之后成功。

总结:其实这个方法并不是最佳方案,因为这样子,就要维护两个hibernate.cfg.xml
。对于一个开发人员,这无疑增加自己负担的事情。如果有哪位知道更好的解决方案,望不吝赐教。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: