With Swift, a singleton initializer is called twice when running XCTest unit tests.
No problems with Objective-C, though, the init() method is only called once, as expected.
Here's how to build the two test projects:
Objective-C
Singleton Class
Create an empty Objective-C Project with tests. Add following bare-bones singleton:
#import "Singleton.h"
@implementation Singleton
+ (Singleton *)sharedInstance
{
static Singleton *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[Singleton alloc] init];
// Do any other initialisation stuff here
});
return sharedInstance;
}
- (instancetype)init
{
self = [super init];
if (self) {
NSLog(@"%@", self);
}
return self;
}
@end
AppDelegate
In the application delegate add a call to the singleton like this:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[Singleton sharedInstance];
return YES;
}
XCTestCase
Also add a call to the singleton to the generated test class:
- (void)testExample {
[Singleton sharedInstance];
// This is an example of a functional test case.
XCTAssert(YES, @"Pass");
}
Results
If you add a breakpoint to the singleton's init
method and run the tests, the breakpoint will only be hit once, as expected.
Swift
Now do the create a new Swift project and do the same thing.
Singleton
Create a singleton, add the test target to its Target Memberships
class Singleton {
class var sharedInstance : Singleton {
struct Static {
static var onceToken : dispatch_once_t = 0
static var instance : Singleton? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = Singleton()
}
return Static.instance!
}
init() {
NSLog("\(self)")
}
}
AppDelegate
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
Singleton.sharedInstance
return true
}
XCTestCase
func testExample() {
// This is an example of a functional test case.
Singleton.sharedInstance
XCTAssert(true, "Pass")
}
Results
This time, if you add a breakpoint to the singleton's init
method and run the tests, the breakpoint will be hit twice, first from the app delegate, then from the test case, i.e. you'll have two instances of the singleton.
Am I missing anything?