3

I have an open source library which has plenty of unit tests that compare string forms of numbers.

These tests pass fine in en-GB, en-US and other cultures where numbers are generally written in the form 1,234.00.

However in cultures such as Germany and France, these values are formatted differently, and the tests fail.

How can the jUnit tests be forced to run as en-GB?

EDIT this kind of thing is available in NUnit.

Community
  • 1
  • 1
Drew Noakes
  • 300,895
  • 165
  • 679
  • 742

3 Answers3

4

I'm not sure it's standard for all JVMs, but using Oracle's JVM on Windows, you can use the user.language and user.country System properties to set the locale when starting the JVM:

java -Duser.language=en -Duser.country=GB ...

You can also, of course, set the default locale in Java, using

Locale.setDefault(new Locale("en", "GB"));

Note that Double.toString is locale-independent, though.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • I had to use the second approach, as I can't control the JVM of developers running tests from my library through their IDEs (for example). However I'm concerned that after calling this, the locale will remain set as en-GB for other tests too, potentially making tests from other code bases fail. Do you know of a way to limit the time over which this locale applies, without having to call getLocale/setLocale in @Before/@After methods? – Drew Noakes Nov 23 '11 at 09:44
1

How do you launch jUnit?

Passing the appropriate language property will depend more of your environment than of jUnit itself.

Alternatively (and I think it's a better solution), you could compare values rather than strings:

assertEquals(12.3, Double.valueOf(aDoubleString));
assertEquals(Double.toString(12.3), aDoubleString);

rather than

assertEquals("12.3", aDoubleString)
ptyx
  • 4,074
  • 1
  • 19
  • 21
  • this is an open source library, so I cannot control how others launch jUnit. Your idea is an interesting one, but isn't the parsing of strings into doubles also governed by culture-specific rules? – Drew Noakes Dec 02 '11 at 09:12
  • That's the point. "12.3" might be "12,3" in France. But while assertEquals("12.3", "12,3") would fail hopefully valueOf (or some other NumberFormat local-friendly parsing method) would interpret the value correctly. – ptyx Dec 14 '11 at 00:28
  • I was referring to `Double.valueOf`, and whether it would treat `"1.234"` and `"1,234"` as the same value irrespective of locale. My guess is that it cannot, and so the problem shifts from the locale of formatting to the locale of parsing. I will keep this in mind when I address the problem, so thanks again for your idea. – Drew Noakes Dec 16 '11 at 16:43
0

there are two gists with JUnit 4 rules to modify the default locale for a couple of tests:

LocaleRule, a very simple implementation.

DefaultLocaleRule has some static helper methods and allows to switch the default locale for an individual test.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820