在测试 iOS Swift 中访问只读属性



我对 iOS 和 Swift 很陌生,目前我在编写单元测试时遇到了问题。我有一个类(假设它被称为 A(,它具有(来自 Objective-C 的只读属性(,在我的测试中,我想将此类的对象传递给稍后使用它做某事的方法。哦,我也没有任何初始值设定项...我的问题是,如何测试这种想法?也许我必须以某种方式嘲笑这样的对象?

------编辑-----

好。我的帖子不是很精确。好的,所以我只知道 Swift 的基础知识(不幸的是,我现在没有时间学习 Objective - C,因为我被要求用 Swift 编写 sth(。我有一个由一些公司提供的类,其中我有一个类(用Objective-C编写(,如下所示:

@interface MainClassX : NSObject
@property (nonatomic, strong, readonly) NSString* code;
@property (nonatomic, strong, readonly) NSArray<XYZ*>* classification;
@end

在我的测试中,想要创建此类的对象并至少初始化"代码"属性......但是二传手是私人的,所以我不能做任何"继承技巧"......?有什么选择可以做还是我应该用另一种方式做?问题是我想测试一种方法,该方法接受此类对象的数组并对其进行处理。

这非常棘手,因为他们希望这些属性是只读的,为什么要测试它们?

无论目的如何,您都可以执行以下步骤: 1. 考虑使用 Category(在 Objective C 中(或 extension(在 Swift 中(向该类添加方法。 2. 实现新的 init 方法,使用键值编程设置适当的code

我已经设法在 Objective C 中快速完成,转换为 Swift 非常简单。

@implementation MainClassX(Test)
-(instancetype)initWithCode:(NSString *)code {
self = [self init];
if (self) {
[self setValue:code forKey:@"code"];
}
return self;
}
@end

测试一下:

MainClassX *test = [[MainClassX alloc] initWithCode:@"TEST"];
NSLog(@"code: %@", test.code); // Should print out "TEST" in the console

迅速:

extension MainClassX {
convenience init(_ code: String) {
self.init()
self.setValue(code, forKey: "code")
}
}

在单元测试中:

import XCTest
@testable import YourAppModule

class YourAppModuleTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
let cls = MainClassX("TEST")
XCTAssert(cls.code == "TEST")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}

您可能正在寻找依赖注入。这是一种可以使用可选值初始化类的方法,该可选值可以根据需要设置测试值。

下面是一个简单的示例。

为 Objective-C 类创建一个可选的初始化:

- (instancetype)initWithOption:(NSString *)option {
self = [super init];
if (self) {
self.option = option;
}
return self;
}

你可以这样,当你通常调用类时,你调用它的默认初始化。但是为了进行测试,请使用此函数对其进行初始化。如果您可能希望拥有一个仅在单元测试中使用的受保护的头文件(例如classname_protected.h(,以便不会向应用程序公开此函数,则需要考虑的另一件事。

如果没有看到更多的测试,添加它有点困难,但 DI 可能是您需要去的地方。

最新更新