作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在尝试测试一个使用类的某些私有(private)属性的类的方法。我四处寻找有关如何在单元测试中访问它们的最佳实践,并决定在我的测试实现文件中为该类添加一个类别。它仍然不允许我访问它们,我收到“未识别的选择器发送到实例”错误。
我的实现类属性定义(在 ImplementationClass.m 文件的顶部):
@interface ImplementationClass () {
TWPLoadUnitEnum loadUnit;
BOOL recosMatchTargets;
}
我的测试类顶部的类别:
//interface to expose private variables of test case class
@interface ImplementationClass (Test)
@property(readwrite,assign) TWPLoadUnitEnum loadUnit;
@property(readwrite,assign) BOOL recosMatchTargets;
@end
我在哪里访问属性:
ImplementationClass *realRecosModal = [[ImplementationClass alloc]
initWithNibName:@"ImplementationClassVC" bundle:nil];
[realRecosModal setLoadUnit:TWPLoadUnitKg]
我在调用“setLoadUnit”的行中收到错误。我没有正确公开私有(private)属性(property)吗?
最佳答案
@interface ImplementationClass () {
TWPLoadUnitEnum loadUnit;
BOOL recosMatchTargets;
}
不是属性,它们是 iVar。如果你想让它们成为属性,你需要有
@interface ImplementationClass ()
@property (nonatomic) TWPLoadUnitEnum loadUnit;
@property (nonatomic) BOOL recosMatchTargets;
如果你想保留 iVar,那么在你的单元测试中放
@interface ImplementationClass () {
@public
TWPLoadUnitEnum loadUnit;
BOOL recosMatchTargets;
}
@end
()
而不是(Test)
。它看起来很奇怪,但它会起作用。关于ios - 如何在 iOS 单元测试中公开私有(private)属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30129537/
我是一名优秀的程序员,十分优秀!