Skip to content

Instantly share code, notes, and snippets.

@digulla
Last active March 9, 2022 17:16
Show Gist options
  • Save digulla/5884162 to your computer and use it in GitHub Desktop.
Save digulla/5884162 to your computer and use it in GitHub Desktop.
JUnit 4 Rule to run individual tests with a different default locale
import java.util.Locale;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
public class DefaultLocaleRule extends TestWatcher {
private Locale originalDefault;
private Locale currentDefault;
public DefaultLocaleRule() {
this( null );
}
public DefaultLocaleRule( Locale defaultForTests ) {
currentDefault = defaultForTests;
}
@Override
protected void starting( Description description ) {
originalDefault = Locale.getDefault();
if( null != currentDefault ) {
Locale.setDefault( currentDefault );
}
}
@Override
protected void finished( Description description ) {
Locale.setDefault( originalDefault );
}
public void setDefault( Locale locale ) {
if( null == locale ) {
locale = originalDefault;
}
Locale.setDefault( locale );
}
public static DefaultLocaleRule en() {
return new DefaultLocaleRule( Locale.ENGLISH );
}
public static DefaultLocaleRule de() {
return new DefaultLocaleRule( Locale.GERMAN );
}
public static DefaultLocaleRule fr() {
return new DefaultLocaleRule( Locale.FRENCH );
}
}
To use the rule, add this to your JUnit test class:
// make all tests run with the English locale
@Rule
public DefaultLocaleRule defaultLocaleRule = DefaultLocaleRule.en();
If a test has special demands, you can switch:
@Test
public void testDE() {
defaultLocaleRule.setDefault( Locale.GERMAN );
...
}
@belgoros
Copy link

I found the reason. It seems like @BeforeClass block are run first, then @rule block is run. So the solute I found is to replace the @rule annotation with @ClassRule that is run before @BeforeClass block and the rule variable should be static:

@ClassRule
    public static DefaultLocaleRule defaultLocaleRule = DefaultLocaleRule.fr();

    @BeforeClass
    public static void setUp() {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment