在单元测试中,验证使用参数NSData调用的函数(其中包含NSString)

时间:2016-06-08 21:23:49

标签: ios objective-c unit-testing ocmock

我正在使用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]);
}

我想验证函数handleData:(NSData*)是否使用包含虚拟字符串NSData的{​​{1}}参数调用,但它失败了,即使真正的实现 >调用@"dummy info",其中handleData:(NSData*)对象从文件中读取 包含NSData NSString

我的意思是看起来像@"dummy info" 只是无法验证,是不是因为OCMVerify()没有从文件中读取?

如何测试dummyInfoData是否使用包含虚拟字符串handleData:(NSData*)的{​​{1}}类型参数调用?

1 个答案:

答案 0 :(得分:1)

NSData旨在从各种来源封装各种格式的数据,因此具有相同行为的两个NSData对象实际上不可能实际相同。在这种情况下,测试实例可能保留了NSString的副本,并且实现实例可能保留了文件句柄,至少在它被使用之前。

在这种情况下,您可能希望在checkWithBlock:上使用OCMArg,然后在那里可以查看课程和内容。您应该比较字符串而不是NSData表示,因此请比较dummyInfoStr[[NSString alloc] initWithData: infoData, encoding: NSUTF8StringEncoding]