JUnit 5 pioneer provides @DefaultLocale
annotation to temporarily change the locale value for test execution. Once the test execution completes, its default value will be restored.
@DefaultLocale
can be configured in multiple ways.
@DefaultLocale(language = "en")
@DefaultLocale(language = "en", country = "EN")
@DefaultLocale(language = "en", country = "EN", variant = "gb")
package com.example.junit5.sujan;
import java.util.Locale;
public class AppleCalculator {
Locale getLanguage() {
Locale locale = new Locale("en");
return locale;
}
Locale getLanguageCountryTest() {
Locale locale = new Locale("en", "EN");
return locale;
}
Locale getLanguageCountryVariant() {
Locale locale = new Locale("en", "EN", "gb");
return locale;
}
}
package com.example.junit5.sujan;
import org.junit.jupiter.api.Test;
import org.junitpioneer.jupiter.DefaultLocale;
import java.util.Locale;
import static org.junit.jupiter.api.Assertions.assertEquals;
class AppleCalculatorTest {
@Test
@DefaultLocale(language = "en")
void languageTest() {
AppleCalculator appleCalculator = new AppleCalculator();
assertEquals(Locale.getDefault(), appleCalculator.getLanguage());
}
@Test
@DefaultLocale(language = "en", country = "EN")
void languageCountryTest() {
AppleCalculator appleCalculator = new AppleCalculator();
assertEquals(Locale.getDefault(), appleCalculator.getLanguageCountryTest());
}
@Test
@DefaultLocale(language = "en", country = "EN", variant = "gb")
void languageCountryVariantTest() {
AppleCalculator appleCalculator = new AppleCalculator();
assertEquals(Locale.getDefault(), appleCalculator.getLanguageCountryVariant());
}
}
plugins {
id 'java'
}
group 'org.example'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
testImplementation('org.junit.jupiter:junit-jupiter:5.6.2')
testCompile 'org.junit-pioneer:junit-pioneer:0.6.0'
}
JUnit Jupiter @
DefaultLocale is a repeatable annotation so if we need to change locale for multiple test cases then instead of writing @
DefaultLocale on each test case, we can annotate class as well, it will temporarily default locale for all the test cases of that class. Once the test execution completes, its default value will be restored.