OGeek|极客世界-中国程序员成长平台

标题: ios - 如何在 iOS 单元测试中公开私有(private)属性? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 15:16
标题: ios - 如何在 iOS 单元测试中公开私有(private)属性?

我正在尝试测试一个使用类的一些私有(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)吗?



Best Answer-推荐答案


@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

关于ios - 如何在 iOS 单元测试中公开私有(private)属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30129537/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4