Is there a way to force a specific locale when running unittests?
Eg. always use en_US or force no locale, so that none of the .lproj files are loaded.
My unittest is sensitive to the currently selected language in the Settings app (in the iOS Simulator). Preferably I would like my unittests not to be language sensitive.
Below is my unittest code that shows the problem
@interface MYGalleryTests : SenTestCase
@end
@implementation MYGalleryTests
-(void)test0 {
// This test doesn't work.
// I get 'No pictures' when locale is en_US
// I get 'Ingen billeder' when locale is da_DK
NSString* actual = [MYGallery emptyMessage];
NSString* expected = @"EMPTY_MESSAGE";
STAssertEqualObjects(actual, expected, nil);
}
@end
@interface MYGallery : NSObject
+(NSString*)emptyMessage;
@end
@implementation MYGallery
+(NSString*)emptyMessage {
return NSLocalizedStringFromTable(@"EMPTY_MESSAGE", @"Gallery", @"Message shown when gallery is empty");
}
@end
en.lproj/Gallery.strings
/* Message shown when gallery is empty */
"EMPTY_MESSAGE" = "No pictures";
da.lproj/Gallery.strings
/* Message shown when gallery is empty */
"EMPTY_MESSAGE" = "Ingen billeder";
There is a way to run the unit tests in a specific locale, but it isn't good for unit testing, but it can be useful for testing.
In Xcode, go to Product -> Scheme -> Edit Scheme… -> select Test -> Options and then set the 'Application Language' popup to the desired language. Then your unit tests will run in the specified language. You can use this to test code for a specific locale. You can use this to get faster test turnaround than actually running your app, especially if you only run a specific subset of unit tests. However, it is not useful for unit testing in general because you're limited to the specified language.
Also, doing this will modify your .xcscheme, so you'll need to change that back when you're done.
One way to change the locale for unit testing is to use the technique specified here. However, that technique uses method swizzling, which doesn't work with Swift.
Just specify the lang in run options.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With