While developing a set of date calculations and language rules for converting numeric values and dates to strings, I'm writing tests that assert the outcome of the string formatting method. An imaginary assertion for it might looks like this:
NSAssert([dateString isEqualToString:@"Three days, until 6:00 PM"], @"Date string should match expectation");
However, because the app is localized for several languages, and my fellow developers are also from and in different locales than I, it can happen that your device or simulator is set to a different locale than the one that the tests are being written for. In a scenario like this, the contents of the dateString
might be something like:
@"Drie dagen, tot 18:00" // the assertion fails
@"Drei Tage, bis 18 Uhr" // the assertion also fails
This may or may not be the correct date notation for these locales, but the part that my question is about, is how to be able to run tests to a specific locale, when the underlying code makes use of Apple API like this:
[NSDateFormatter localizedStringFromDate:date
dateStyle:NSDateFormatterNoStyle
timeStyle:NSDateFormatterShortStyle];
I would love to cover at two or more languages in my assertions, with something like this:
[NSSomething actionToSetTheLocaleTo:@"en_US"];
dateString = ...; // the formatting
NSAssert([dateString isEqualToString:@"Three days, until 6:00 PM"], @"match en_US");
[NSSomething actionToSetTheLocaleTo:@"nl_NL"];
dateString = ...; // the formatting
NSAssert([dateString isEqualToString:@"Drie dagen, tot 18:00"], @"match nl_NL");
Who knows how to achieve this effect?
Notes:
- Changing the preferred language does not cut it, it also needs to influence the NSDateFormatter and NSNumberFormatter behavior.
- Because this is for unit testing purposes only, I'd be content with using private API. However, for the benefit of other people stumbling on this post, public API is preferred.
- Passing a custom locale to each and every date or number formatting API might be a final consideration, but I'm posting this question hoping to avoid falling back to those extreme measures. If you however know this to be the only solution, please provide some reference and I'll waste no more time
Links on the topic: