Java unit test can't access ResourceBundle
Asked Answered
S

1

6

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"));

The resource file lives in the web package at Mycompany_web/src/main/webapp/WEB-INF/classes/businessVariables.properties

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?

Schlegel answered 30/5, 2012 at 12:53 Comment(2)
Have you tried renaming the bundle to suite the en_Us locale? see #2083659Balbriggan
Anyway, following Kaylan's answer, /webapp/WEB-INF/classes seems like a the target folder. Look into your project structure - the bundle file would better be in e.g. Mycompany_web/src/main/resources/businessVariables.propertiesBalbriggan
A
6

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.

While packaging the war, copy the resource bundle from Mycompany_xml/src/test/resources to the war using maven-assembly-plugin.

Ashling answered 30/5, 2012 at 13:0 Comment(1)
This is correct. However, also note that the pom file can define an alternative place to put the resources file.e.g <testResources> <testResource> <directory>${basedir}/conf</directory> </testResource> </testResources>Schlegel

© 2022 - 2024 — McMap. All rights reserved.