我有以下课程:
@interface ReportsArchiver
-(void)fileReport:(NSDictionary*)reports;
@end
@interface OfficeManager
@property (nonatomic) ReportsArchiver* reportsArchiver;
-(void) reportIncident:(NSString*)name description:(NSString*)description;
@end
使用OCMock我想在调用[officeManager reportIncident:@"fire alarm" description: @"false fire alarm"]
时进行测试,然后使用字典[officeManager.reportsArchiver fileReport]
调用@{@"name": @"fire alarm", @"description": @"false fire alarm"}
。
到目前为止,我已经编写了以下代码:
OfficeManager* officeManager = [OfficeManager new];
id reportsArchiverMock = OCMClassMock([ReportsArchiver class]);
officeManager.reportsArchiver = reportsArchiverMock;
NSDictionary* expectedReportDictionary = @{@"name": @"fire alarm", @"description": @"false fire alarm"};
[officeManager reportIncident:@"fire alarm" description: @"false fire alarm"];
// This call will fail because it checks for object equality, not dictionary equality.
OCMVerify([reportsArchiverMock fileReport:expectedReportDictionary]);
如何验证使用OCMock使用相同的NSDictionary调用[reportsArchiverMock fileReport:{(NSDictionary*)]
?
答案 0 :(得分:2)
从那时起,我从Twitter获得了@wolffan和@catehstn的建议,以下是我找到的解决方案。
使用OCMExpect
- 与OCMVerify
不同,OCMExpect
正确地比较NSDictionaries
。这是我发现的最干净的解决方案。
OfficeManager* officeManager = [OfficeManager new];
id reportsArchiverMock = OCMClassMock([ReportsArchiver class]);
officeManager.reportsArchiver = reportsArchiverMock;
NSDictionary* expectedReportDictionary = @{@"name": @"fire alarm", @"description": @"false fire alarm"};
OCMExpect([reportsArchiverMock fileReport:expectedReportDictionary])
[officeManager reportIncident:@"fire alarm" description: @"false fire alarm"];
OCMVerifyAll(reportsArchiverMock);
OCMStub
并检查回调中的参数。这是一个非常混乱的解决方案。
OfficeManager* officeManager = [OfficeManager new]
id reportsArchiverMock = OCMClassMock([ReportsArchiver class]);
officeManager.reportsArchiver = reportsArchiverMock;
NSDictionary* expectedReportDictionary = @{@"name": @"fire alarm", @"description": @"false fire alarm"};
void (^reportIncidentInvocation)(NSInvocation *) = ^(NSInvocation *invocation) {
__unsafe_unretained NSInvocationOperation *reportDictionary;
[invocation getArgument: &reportDictionary atIndex: 2];
XCTAssertTrue([expectedPropertiesCollection isEqualToDictionary:(NSDictionary*)reportDictionary]);
};
OCMStub([officeManager reportIncident:[OCMArg any]]).andDo(reportIncidentInvocation);
OCMVerify([reportsArchiverMock fileReport:expectedReportDictionary]);