Java unit test can't access ResourceBundle

10,833

Solution 1

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.

Solution 2

Add

Mycompany_web/src/main/webapp/WEB-INF/classes/

to the classpath your unit test is running in.

Share:
10,833
Andy A
Author by

Andy A

A software engineer with experience in Java, Hibernate, Android and Cocoa-touch.

Updated on June 23, 2022

Comments

  • Andy A
    Andy A almost 2 years

    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?