2015-04-07 63 views
0

我有以下類別:OCMock:測試方法有一個NSDictionary參數被調用

@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]); 

我如何可以驗證該[reportsArchiverMock fileReport:{(NSDictionary*)]被調用,相同的NSDictionary使用OCMock?

回答

1

從那時起,我通過Twitter從@wolffan和@catehstn得到了建議,這裏是我找到的解決方案。

  1. 使用OCMExpect - 不像OCMVerifyOCMExpect正確比較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); 
    
  2. 使用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]); 
+1

這很奇怪。使用驗證或預期應該沒有區別。如果存在對象相等與字典相等的問題,那麼這也應該與期望一起發生。 (我說這是OCMock的維護者。)你介意在Github上打開一個問題,最好對OCMock進行失敗的單元測試嗎? –

+0

感謝您的回覆@ErikDoernenburg。我會嘗試通過單元測試來重現這一點,並打開一個問題。 –

相關問題