Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 394
user3453784 Avatar asked Dec 05 '14 22:12

user3453784


People also ask

How do I change the default locale in Java?

Java Locale setDefault() method The setDefault() method of Java Locale class is used to set the default locale for this instance of the JVM(Java Virtual Machine). It does not affect the host locale.

How to update locale in Java?

In Java, we can use Locale. setDefault() to change the JVM default locale. Alternatively, in the command line, we can configure the user. country and user.


1 Answers

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.

like image 80
rgettman Avatar answered Sep 23 '22 06:09

rgettman