测试用例中的NSData比较



概述:

有一个函数f1返回NSData

有没有一种方法可以编写一个测试用例来测试返回NSData的函数?

如何创建变量expectedOutput(请参阅下面的代码)?

示例:

@interface Car : NSObject
- (NSData*) f1;
@end
@implementation Car
- (NSData*) f1 {
    NSData *someData = [[NSData alloc] init]; //This is just an example, the real code has some logic to build the NSData
    return someData;
}
@end

测试用例:

- (void) test {
    Car *c1;
    NSData *actualOutput = [c1 f1];
    NSData *expectedOutput = ??? //How can I build this NSData ?
    XCTAssertEqualObjects(actualOutput, expectedOutput);
}

构建预期输出的方法取决于NSData的内容。它应该基于f1的含义。
若您不知道应该生成f1的数据类型,可以检查返回的NSData的长度和类(若您知道以字节为单位的长度)
如果您知道f1将某个字符串编码为数据,那么您可以生成一个目标字符串,并将生成的字符串与从返回的数据中创建的字符串进行比较
如果您知道应该生成此函数的字节序列(例如,您在其他语言上有相同的函数,或者有标准位字节),您可以将字节从光盘加载到NSData,并将其与actualOutput进行比较。

步骤

  1. expectedOutputNSData)写入文件(一次)
  2. 在测试用例中,读取文件并填充expectedOutput
  3. 比较expectedOutputactualOutput

步骤1:

    - (void) writeExpectedDataToFile {}
        //Write expected data to file (to be done only once)
        NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docsDir = [dirPaths objectAtIndex:0];
        NSString *databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:@"expected.txt"]];
        [data writeToFile:databasePath atomically:YES];
    }

步骤2:

    - (void) test {
        Car *c1;
        NSData *actualOutput = [c1 f1];
        //Reading from file
        NSBundle* bundle = [NSBundle bundleForClass:[self class]];
        NSURL* fileName1 = [bundle URLForResource:@"expected" withExtension:@"txt"];
        NSData *expectedData = [NSData dataWithContentsOfFile:[fileName1.path stringByExpandingTildeInPath]];
        XCTAssertEqualObjects(actualOutput, expectedOutput);
}

最新更新