Objective C - 如何测试私有变量

Objective C - how to test private variables

如何对隐藏变量 aVar 进行单元测试?

// .h file    
@interface Class: NSObject

@end

// .m file    
@implementation Class{
 id aVar
}

@end

您可以使用 KVC [obj setValue:<value> forKey:<key>] 关于 KVC 的详细信息点击 here

您可以将您的私有变量移动到 class extension,这样可以使它们保持私有,然后创建一个 -Private 类别,使它们成为 public。例如。

// Class.h
@interface Class : NSObject
@end

// Class.m
@interface Class ()
@property (nonatomic, strong) id aVar;
@end

@implementation Class
@end

// Class+Private.h
@interface Class (Private)
@property (nonatomic, strong) id aVar;
@end

...

然后 import/compile Class+在您的单元测试目标中私有化。