Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run unittests with a specific locale (en_US or none)

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";
like image 906
neoneye Avatar asked Jul 29 '13 16:07

neoneye


2 Answers

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.

like image 141
ThomasW Avatar answered Sep 21 '22 04:09

ThomasW


Just specify the lang in run options.

enter image description here

like image 37
Mike Glukhov Avatar answered Sep 25 '22 04:09

Mike Glukhov