Under ARC
,我有一个对象,Child
有一个weak
财产,parent
。我正在尝试编写一些测试Child
,我嘲笑它parent
财产使用OCMock
.
在 ARC 下,设置NSProxy
使用合成弱属性设置器的子类不会设置属性...设置弱属性后的行,检查它发现它已经nil
。这是具体的例子:
@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
,但那时我必须nil
出parent
当我完成它时(就像某种穴居人),这正是 ARC 应该避免的事情。
关于如何在不更改我的应用程序代码的情况下通过此测试有什么建议吗?
Edit: 好像也有关系OCMockObject
是一个NSProxy
,如果我做aParent
是一个实例NSObject
, the child.parent
弱引用“持有”非零值。仍在寻找一种无需更改应用程序代码即可通过此测试的方法。
Edit 2:接受布莱克的回答后,我在我的项目中实现了一个预处理器宏,该宏有条件地更改了我的属性,从弱到分配。你的旅费可能会改变:
#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