The @DefaultLocale and @DefaultTimeZone annotations can be used to change the values returned from Locale.getDefault() and TimeZone.getDefault(). Both annotations work on the test class level and on the test method level. After the annotated element has been executed the initial default value is restored.

@DefaultLocale

The default Locale can be specified using an IETF BCP 47 language tag string

@Test
@DefaultLocale("zh-Hant-TW")
void test_with_lanuage() {
    assertEquals(Locale.forLanguageTag("zh-Hant-TW"), Locale.getDefault());
}

Alternatively the default Locale can be specified according to its constructors - it needs either:

  • language or

  • language and country or

  • language, country, and variant

@Test
@DefaultLocale(language = "en")
void test_with_lanuage() {
    assertEquals(new Locale("en"), Locale.getDefault());
}

@Test
@DefaultLocale(language = "en", country = "EN")
void test_with_lanuage_and_country() {
    assertEquals(new Locale("en", "EN"), Locale.getDefault());
}

@Test
@DefaultLocale(language = "en", country = "EN", variant = "gb")
void test_with_lanuage_and_country_and_vairant() {
    assertEquals(new Locale("en", "EN", "gb"), Locale.getDefault());
}

Note that mixing language tag configuration and constructor based configuration will cause an ExtensionConfigurationException to be thrown. Furthermore a variant can only be specified if country is also specified. If variant is specified without country, an ExtensionConfigurationException will be thrown.

Any method level @DefaultLocale configurations will override class level configurations.

@DefaultLocale(language = "fr")
class MyLocaleTests {

    @Test
    void test_with_class_level_configuration() {
        assertEquals(new Locale("fr"), Locale.getDefault());
    }

    @Test
    @DefaultLocale(language = "en")
    void test_with_method_level_configuration() {
        assertEquals(new Locale("en"), Locale.getDefault());
    }
}

@DefaultTimeZone

The default TimeZone is specified according to the TimeZone.getTimeZone(String) method.

@Test
@DefaulTimeZone("CET")
void test_with_short_zone_id() {
    assertEquals(TimeZone.getTimeZone("CET"), TimeZone.getDefault());
}

@Test
@DefaultTimeZone("America/Los_Angeles")
void test_with_long_zone_id() {
    assertEquals(TimeZone.getTimeZone("America/Los_Angeles"), TimeZone.getDefault());
}

Any method level @DefaultTimeZone configurations will override class level configurations:

@DefaultTimeZone("CET")
class MyTimeZoneTests {

    @Test
    void test_with_class_level_configuration() {
        assertEquals(TimeZone.getTimeZone("CET"), TimeZone.getDefault());
    }

    @Test
    @DefaultTimeZone("America/Los_Angeles")
    void test_with_method_level_configuration() {
        assertEquals(TimeZone.getTimeZone("America/Los_Angeles"), TimeZone.getDefault());
    }
}

Updated: