gpt4 book ai didi

ios - Swift Singleton Init 在 XCTest 中被调用两次

转载 作者:IT王子 更新时间:2023-10-29 05:50:13 26 4
gpt4 key购买 nike

在 Swift 中,单例初始化器在运行 XCTest 单元测试时被调用两次

不过,使用 Objective-C 没有问题,正如预期的那样,init() 方法只被调用一次。

以下是构建两个测试项目的方法:

objective-C

单例类

创建一个带有测试的空 Objective-C 项目。添加以下准系统单例:

#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

应用委托(delegate)

在应用程序委托(delegate)中添加对单例的调用,如下所示:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[Singleton sharedInstance];
return YES;
}

XC测试用例

同时在生成的测试类中添加对单例的调用:

- (void)testExample {
[Singleton sharedInstance];
// This is an example of a functional test case.
XCTAssert(YES, @"Pass");
}

结果

如果您将断点添加到单例的 init 方法并运行测试,断点只会命中一次,正如预期的那样。

swift

现在创建一个新的 Swift 项目并执行相同的操作。

单例

创建一个单例,将测试目标添加到它的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)")
}
}

应用委托(delegate)

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
Singleton.sharedInstance
return true
}

XC测试用例

func testExample() {
// This is an example of a functional test case.
Singleton.sharedInstance
XCTAssert(true, "Pass")
}

结果

这一次,如果您将断点添加到单例的 init 方法并运行测试,断点将被命中两次,首先是来自应用程序委托(delegate),然后是来自测试用例,即您将拥有两个单例实例。

我错过了什么吗?

最佳答案

由于应用模块和测试模块是分离的模块,当你添加Singleton.swift文件到测试目标成员时,YourApp.SingletonYourAppTest.Singleton 不是同一个类。这就是 init 调用两次的原因。

除此之外,您应该在测试文件中导入您的主模块:

import YourAppName

func testExample() {
// This is an example of a functional test case.
Singleton.sharedInstance
XCTAssert(true, "Pass")
}

和您的 Singleton 类必须声明为 public。见Swift, access modifiers and unit testing

public class Singleton {
public 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)")
}
}

不要忘记从测试目标成员中删除 Singleton.swift

关于ios - Swift Singleton Init 在 XCTest 中被调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27172481/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com