Skip to content

Instantly share code, notes, and snippets.

@rponte
Last active September 23, 2017 17:48
Show Gist options
  • Save rponte/5289883 to your computer and use it in GitHub Desktop.
Save rponte/5289883 to your computer and use it in GitHub Desktop.
JUnit Rule which allows to use specific locale for particular tests.
import java.util.Locale;
/**
* Rule allows to use specific locale for particular tests.
*
* Default locale is stored before test and restored after.
* Rule can be used on the method or class level.
*
* @author setkomac
*
*/
public class LocaleRule extends InitializationRule {
private static final Locale defaultLocale = Locale.getDefault();
private Locale locale;
/**
* Object constructor.
* @param locale Local that will be used inside test.
*/
public LocaleRule(Locale locale){
this.locale = locale;
}
@Override
public void before() {
Locale.setDefault(locale);
}
@Override
public void after() {
Locale.setDefault(defaultLocale);
}
}
import java.util.Locale;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
public class MyLocaleRule implements TestRule {
private static final Locale defaultLocale = Locale.getDefault();
private final Locale locale;
public MyLocaleRule(Locale locale) {
this.locale = locale;
}
@Override
public Statement apply(final Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
Locale.setDefault(locale);
try {
base.evaluate();
} catch (Throwable t) {
throw t;
} finally {
Locale.setDefault(defaultLocale);
}
}
};
}
}
import java.util.Locale;
import org.junit.rules.ExternalResource;
public class MyLocaleRuleUsingExternalResource extends ExternalResource {
private static final Locale defaultLocale = Locale.getDefault();
private final Locale locale;
public MyLocaleRuleUsingExternalResource(Locale locale) {
this.locale = locale;
}
@Override
protected void before() throws Throwable {
Locale.setDefault(locale);
}
@Override
protected void after() {
Locale.setDefault(defaultLocale);
}
}
@rponte
Copy link
Author

rponte commented Apr 2, 2013

@rponte
Copy link
Author

rponte commented Dec 23, 2013

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