简体   繁体   中英

Running a localized Test with TestNG

I'm stuck here:

My scenario: I'm running a test with TestNG where I call a function of a 3rd party library. This library gets initialized with Locale.getDefault().

To get the same test result independently from the machine the test is run on, I want to set a specific Locale and reset it afterwards. Unfortunately, it seems that though I can set the Locale to my desired value, some other tests (not in the same testClass) fail... probably due to formatting issues (localization).

private Locale locale;

@BeforeClass
public void init() {
    locale = Locale.getDefault();
    Locale.setDefault(Locale.US);
}

@AfterClass
public void teardown() {
    Locale.setDefault(locale);
}

@Test(dataProvider = "someDataProvider")
public void testThisWithUSLocale(String element) throws Exception {
    String resultToTest = myClass.createSomething(element);

    Assert.assertFalse(resultToTest.isEmpty());
}

I tried setting Locale in @BeforeMethod but had the same issue... Are tests run async? does setting the Locale in this test really affect the other tests?

Changing the locale while the JVM is running is a tricky process, and the whole application needs to be prepared for it. From the javadocs of setDefault

Since changing the default locale may affect many different areas of functionality, this method should only be used if the caller is prepared to reinitialize locale-sensitive code running within the same Java Virtual Machine.

Your test setup looks correct, but whatever your code (or the 3rd party library) do probably doesn't support a change of the Locale.

Alright, I found the problem:

Locale was initially set for FORMAT. So, by running everything in @BeforeClass , my tests worked fine, but after "resetting" everything with Locale.setDefault(locale);that I saved earlier (but in a wrong way), I'm setting ALL Categories, and not just FORMAT making the other test fail. Correct is:

private Locale locale;

@BeforeClass
public void init() {
        locale = Locale.getDefault(Locale.Category.FORMAT);
        Locale.setDefault(Locale.Category.FORMAT, Locale.US);
}

@AfterClass
public void teardown() {
        Locale.setDefault(locale);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM