Search code examples
javajunitinternationalization

change default locale for junit test


How do you change the default locale for a JUnit Test. Current locale is en. I want to test for es_ES. I tried:

System.setProperty("locale", "es_ES");

But this doesn't seem to work.


Solution

  • You can set the default Locale with Locale.setDefault.

    Sets the default locale for this instance of the Java Virtual Machine. This does not affect the host locale.

    Locale.setDefault(new Locale("es", "ES"));
    

    Testing with the following resource files:

    • test.properties

      message=Yes
      
    • test_es_ES.properties

      message=Sí
      

    Here is my main function, with no change to my default locale (en_US):

    public static void main(String[] args)
    {
        ResourceBundle test = ResourceBundle.getBundle("test");
        System.out.println(test.getString("message"));
    }
    

    Output:

    Yes
    

    Here is my main function, with a change to your test locale (es_ES):

    public static void main(String[] args)
    {
        Locale.setDefault(new Locale("es", "ES"));
        ResourceBundle test = ResourceBundle.getBundle("test");
        System.out.println(test.getString("message"));
    }
    

    Output:

    This should work when applied to a JUnit test case.