[英]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.