Java单元测试无法访问ResourceBundle [英] Java unit test can't access ResourceBundle
问题描述
我正在创建一个Java单元测试来测试我最近更改的一些代码。但是,我正在测试的方法实例化一个使用ResourceBundle的类......
I am creating a Java unit test to test some code I recently changed. However, the method I am testing instantiates a class which uses ResourceBundle …
ResourceBundle.getBundle("businessVariables").getString("product.name"));
资源文件位于Web包中 Mycompany_web / src / main / webapp / WEB-INF / classes / businessVariables.properties
The resource file lives in the web package at Mycompany_web/src/main/webapp/WEB-INF/classes/businessVariables.properties
我的测试存在于我的xml包中 Mycompany_xml / src /test/java/uk/co/mycompany/xmlapi/RequestProcessorTestNew.java
My test lives in my xml package at Mycompany_xml/src/test/java/uk/co/mycompany/xmlapi/RequestProcessorTestNew.java
在正常运行时期间,资源包可以访问,但不能在我的单元测试运行。抛出此错误...
During normal runtime the resource bundle is accessible, but not when my unit test is run. It throws this error …
Testcase: testCreateInitialStatusResponse(uk.co.mycompany.xmlapi.RequestProcessorTestNew): Caused an ERROR
null
java.lang.reflect.InvocationTargetException
at uk.co.mycompany.xmlapi.RequestProcessorTestNew.testCreateInitialStatusResponse(RequestProcessorTestNew.java:62)
Caused by: java.lang.ExceptionInInitializerError
at uk.co.mycompany.xmlapi.RequestProcessorImpl.createInitialStatusResponse(RequestProcessorImpl.java:812)
Caused by: java.util.MissingResourceException: Can't find bundle for base name businessVariables, locale en_US
我该怎么办?我可以启用测试以某种方式查看资源包吗?我可以在某个地方以某种方式创建一个模拟资源文件吗?
What should I do? Can I enable my test to see the resource bundle somehow? Can I create a mock resource file somewhere which somehow the code will be able to see?
推荐答案
如果您已经构建了项目结构根据Maven原型,您的资源包理想情况下应该在Mycompany_xml / src / test / resources中。然后你可以使用mvn test从项目主目录运行单元测试,即Mycompany_xml目录。
If you have build your project structure according to Maven archetype, your resource bundle should ideally be in Mycompany_xml/src/test/resources. Then you can run unit tests from project home i.e. Mycompany_xml directory using mvn test.
打包战争时,将资源包从Mycompany_xml / src / test / resources复制到使用maven-assembly-plugin进行战争。
While packaging the war, copy the resource bundle from Mycompany_xml/src/test/resources to the war using maven-assembly-plugin.
这篇关于Java单元测试无法访问ResourceBundle的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!