Run unittests with a specific locale (en_US or none)
Asked Answered
G

2

15

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";
Girdle answered 29/7, 2013 at 16:15 Comment(2)
Check out #1670145Fatty
This answer is a way to address the issue: https://mcmap.net/q/806788/-change-the-ios-simulator-39-s-current-locale-at-runtimeLuminiferous
L
13

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.

Luminiferous answered 11/1, 2018 at 9:30 Comment(2)
@Serzhas which solution did you use? Edit Scheme or swizzling?Luminiferous
I just edited scheme and explicitly specified which region should be used for tests (Edit Scheme -> Test -> Options -> Application Region). 🤓Uranous
C
9

Just specify the lang in run options.

enter image description here

Curiel answered 30/8, 2019 at 6:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.