簡體   English   中英

在單元測試中,驗證使用參數NSData調用的函數(其中包含NSString)

[英]in unit test, verify function called with argument NSData (with a NSString in it)

我正在使用OCMock v3做單元測試,我想測試一個名為processInfo:的非常簡單的函數,其實現如下所示:

@implementation MyService
-(void) processInfo{
  // get info file path
  NSString *infoFilePath = [self getInfoFile];
  // read info data from infoFile
  NSData *infoData = [[NSData alloc] initWithContentsOfFile:infoFilePath];

  // call another function to handle info data
  [self handleData:infoData];
}

-(void) handleData:(NSData*) infoData {
   ...
}

@end

如您所見, processInfo:函數獲取信息文件路徑並讀取數據,然后調用handleData:(NSData*)函數。 很簡單的邏輯。

我嘗試通過以下方式測試上述簡單功能:

-(void) testProcessInfo{
  // create dummy info string
  NSString* dummyInfoStr = @"dummy info";
  // convert above NSString to NSData object
  NSData* dummyInfoData = [dummyInfoStr dataUsingEncoding:NSUTF8StringEncoding];

  // get the same info file path
  NSString* infoFilePath=[self getInfoFile];
  // write dummy info data to info file
  [data writeToFile:path options:NSDataWritingAtomic error:nil];

  // CALL function under test
  [myServicePartialMock processInfo];

  // I want to verify that handleData:(NSData*) has been invoked with a NSData argument which contains dummy string @"dummy info"
  // BUT it failed, even though the real implementation does it.
  // For some reason the dummyInfoData is not considered equal to the NSData used in real implementation, though they both contain string @"dummy info"
  OCMVerify([myServicePartialMock handleData:dummyInfoData]);
}

我想驗證是否使用包含偽字符串@"dummy info"NSData參數調用了handleData:(NSData*)函數,但是它失敗了,即使實際實現確實通過讀取的NSData對象調用了handleData:(NSData*)從文件,該文件確實包含NSString@"dummy info"

我的意思是看起來像OCMVerify() 只是無法驗證它 ,是因為不從文件讀取dummyInfoData嗎?

我如何測試帶有NSData類型參數(包含偽字符串@"dummy info" handleData:(NSData*)handleData:(NSData*)呢?

NSData旨在封裝來自各種來源的多種格式的數據,因此,具有相同行為的兩個NSData對象實際上不太可能是相同的。 在這種情況下,測試實例可能會保留NSString的副本,而實現實例可能至少要保留文件句柄,直到使用它為止。

在這種情況下,你可能想使用checkWithBlock:OCMArg ,一旦那里你可以檢查類和內容。 您應該比較字符串而不是它們的NSData表示形式,因此要比較dummyInfoStr[[NSString alloc] initWithData: infoData, encoding: NSUTF8StringEncoding]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM