【发布时间】:2015-08-07 06:37:12
【问题描述】:
我正在编写一个单元测试来测试一个更新清单的方法。清单具有以下属性:
typedef NS_ENUM (NSUInteger, ChecklistStatus) { Pending, Completed };
@protocol IChecklistItem <NSObject>
@property (nonatomic, assign, readonly) NSInteger Id;
@property (nonatomic, copy, readonly) NSString *Description;
@property (nonatomic, assign, readonly)BOOL IsCompleted;
@property (nonatomic, assign, readwrite) ChecklistStatus Status;
@property (nonatomic, strong, readwrite) NSDate *CompletedDate;
@property (nonatomic, copy, readwrite) NSString *CompletedByUserId;
@property (nonatomic, assign, readonly) NSInteger RoleId;
@property (nonatomic, assign, readonly) NSInteger GroupId;
@property (nonatomic, strong, readonly) NSArray<IChecklistNote> *Notes;
- (void)sortNotes;
@end
但是,在我的单元测试中,当我试图验证时,
checklistItem.Description = @"hello";,我收到错误“Assignment to readonly property”
为什么会这样?
这是我的测试方法的其余部分:
- (void)testUpdateChecklist {
NSString *testChecklistId = @"1";
NSString *testPatientDescription = @"Descriptive Description";
// What other properties do I need here?
XCTAssertNotNil(_service);
__block CCChecklistItem *checklistItem = nil;
SignalBlocker *blocker = [[SignalBlocker alloc] initWithExpectedSignalCount:1];
id delegate = OCMProtocolMock(@protocol(ChecklistServiceDelegate));
OCMExpect([delegate didCompleteUpdateChecklistItem:[OCMArg checkWithBlock:^BOOL(id obj) {
checklistItem = obj;
XCTAssertNotNil(checklistItem);
[blocker signal];
return true;
}]]);
[_service updateChecklistItem:checklistItem delegate:delegate];
[blocker waitWithTimeout:5.0f];
OCMVerifyAll(delegate);
NSString *originalDescription = checklistItem.Description;
checklistItem.Description = @"hello";
}
编辑问题:
所以当我将属性从上面更改为 ReadWrite 时,我在 CChecklistItem 中收到此错误
@interface CCChecklistItem ()
@property (nonatomic, assign, readwrite) NSInteger Id;
@property (nonatomic, copy, readwrite) NSString *Description;
@property (nonatomic, assign, readwrite) NSInteger RoleId;
@property (nonatomic, assign, readwrite) NSInteger GroupId;
@property (nonatomic, strong, readwrite) NSMutableArray<IChecklistNote> *Notes;
@end
`类扩展'CChecklistItem'中读写属性的非法重新声明
【问题讨论】:
-
你明白
readonly属性属性是什么意思吗? -
1.不要写默认参数,因为那是过时的代码 == 更难阅读(例如
readwrite,可能都是assign和strong)。 2. 在 obj-c 中,我们使用小写首字母命名变量。 3.正如其他答案中所指出的,您可以删除readonly标志:如果您测试此变量的设置,它应该是readwrite。如果它应该是readonly,你不应该尝试在你的测试中设置它。
标签: objective-c