简体   繁体   English

使用 TestNG 运行本地化测试

[英]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.我的场景:我正在使用 TestNG 进行测试,其中我调用了第 3 方库的 function。 This library gets initialized with Locale.getDefault().该库使用 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).不幸的是,似乎虽然我可以将语言环境设置为我想要的值,但其他一些测试(不在同一个 testClass 中)失败了......可能是由于格式问题(本地化)。

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?我尝试在 @BeforeMethod 中设置语言环境,但遇到了同样的问题……测试是否异步运行? 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.在 JVM 运行时更改语言环境是一个棘手的过程,整个应用程序都需要为此做好准备。 From the javadocs of setDefault来自setDefault的 javadocs

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.由于更改默认区域设置可能会影响许多不同的功能区域,因此仅当调用者准备重新初始化在同一 Java 虚拟机中运行的区域设置敏感代码时,才应使用此方法。

Your test setup looks correct, but whatever your code (or the 3rd party library) do probably doesn't support a change of the Locale.您的测试设置看起来正确,但无论您的代码(或第 3 方库)做什么,都可能不支持更改语言环境。

Alright, I found the problem:好吧,我发现了问题:

Locale was initially set for FORMAT.语言环境最初是为 FORMAT 设置的。 So, by running everything in @BeforeClass , my tests worked fine, but after "resetting" everything with Locale.setDefault(locale);因此,通过在@BeforeClass中运行所有内容,我的测试工作正常,但是在使用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.我之前保存的(但以错误的方式),我正在设置所有类别,而不仅仅是 FORMAT 使其他测试失败。 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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