gpt4 book ai didi

ios - 如何在 iOS 单元测试中公开私有(private)属性?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:00:09 24 4
gpt4 key购买 nike

我正在尝试测试一个使用类的某些私有(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)。它看起来很奇怪,但它会起作用。
  • 重要提示:您必须提供所有 iVar,并且它们的顺序必须准确,否则可能会导致意外行为(如随机崩溃)。

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

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