objective-c - 如何让 ARC 下的 OCMock 停止使用弱属性对 NSProxy 子类集进行 nilling?

标签 objective-c unit-testing automatic-ref-counting ocmock nsproxy

ARC 下,我有一个对象 Child,它有一个 weak 属性,parent。我正在尝试为 Child 编写一些测试,并且正在使用 OCMock 模拟其 parent 属性。

在 ARC 下,使用合成的弱属性 setter 设置 NSProxy 子类不会设置属性...设置弱属性后的行,检查它会发现它已经是 。下面是具体的例子:

@interface Child : NSObject
@property (nonatomic, weak) id <ParentInterface>parent;
@end

@implementation Child
@synthesize parent = parent_;
@end

//  ... later, inside a test class ...

- (void)testParentExists
{
    // `mockForProtocol` returns an `NSProxy` subclass
    //
    OCMockObject *aParent = [OCMockObject mockForProtocol:@protocol(ParentInterface)];
    assertThat(aParent, notNilValue());

    // `Child` is the class under test
    //
    Child *child = [[Child alloc] init];
    assertThat(child, notNilValue());

    assertThat(child.parent, nilValue());
    child.parent = (id<ParentInterface>)aParent;
    assertThat([child parent], notNilValue());  // <-- This assertion fails
    [aParent self]; // <-- Added this reference just to ensure `aParent` was valid until the end of the test.
}

我知道我可以使用 assign 属性而不是 weak 属性来解决这个问题,让 Child 引用 Parent,但是当我完成它时,我必须 nilparent(就像某种穴居人),这正是那种ARC 应该避免的事情。

关于如何在不更改我的应用代码的情况下通过此测试的任何建议?

编辑:这似乎与 OCMockObject 是一个 NSProxy 有关,如果我让 aParent 成为NSObject 的一个实例,child.parent 弱引用“持有”一个非零值。仍在寻找一种无需更改应用代码即可通过此测试的方法。

编辑 2:在接受 Blake 的回答后,我在我的项目中实现了一个预处理器宏,有条件地将我的属性从 weak -> assign 更改。您的里程可能会有所不同:

#if __has_feature(objc_arc)
#define BBE_WEAK_PROPERTY(type, name) @property (weak, nonatomic) type name
#else
#define BBE_WEAK_PROPERTY(type, name) @property (assign, nonatomic) type name
#endif

最佳答案

我们一直在努力解决同样的问题,它确实与 ARC 和对 NSProxy 派生对象的弱引用之间的不兼容有关。我建议使用预处理器指令有条件地编译您的弱委托(delegate)引用以在测试套件中分配,以便您可以通过 OCMock 测试它们。

关于objective-c - 如何让 ARC 下的 OCMock 停止使用弱属性对 NSProxy 子类集进行 nilling?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9104544/

相关文章:

objective-c - iPad 的基于 ARC 的项目中内存不足访问崩溃报告

objective-c - 使用 XCodeConfig 设置禁用 Objective C ARC

iphone - 将数据重新加载到 NSArray 时出现问题(可能是因为 ARC)

javascript - 动态更改 Javascript 参数

flutter - 用于 dart/flutter 测试的覆盖/模拟库函数

iphone - ShareKit 变化?

iphone - VFR 阅读器在 IOS 7 中崩溃

ios - Google Analytics 不显示某些页面的跟踪

ios - 点击 UIWebViews 时键盘消失

cocoa-touch - 使用 OCMock 模拟 NSNotificationCenter 有时会失败,除非添加延迟