【发布时间】:2013-05-15 17:06:37
【问题描述】:
我正在尝试为 json 验证编写单元测试(因为该应用严重依赖来自 rest API 的 json)。
我有一个包含简单 json 的本地文件:“goodFeaturedJson.txt”
内容:
{
"test": "TEST"
}
测试用例:
- (void)testJsonIsValid
{
Featured *featured = [Featured new];
NSString* filepath = [[NSBundle mainBundle]pathForResource:@"goodFeaturedJson" ofType:@"text"];
NSData *data = [NSData dataWithContentsOfFile:filepath];
NSString *jsonString = [[NSString alloc] initWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:nil];//[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"The json string is: %@", jsonString);
id JSON = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
STAssertTrue([featured jsonIsValid:JSON], @"Featured Data is NOT valid...");
}
测试每次都失败。控制台打印:
The json string is: (null)
为什么?我知道为什么测试失败了,因为很明显,如果数据为 nil/null,则不会有有效的 json,并且验证器会中断(如果它无效,它应该会中断)。
这里一定有一些简单的东西我错过了,有什么想法吗?
【问题讨论】:
-
类型应该是
ofType:@"txt"? -
如果我这样做,字符串仍然为空。我试过文本,类型为“json”。结果似乎总是一样,我不知道为什么。
-
错误(您显然不会费心检查)说明了什么?
-
*data 是否也为空?
-
JSONObjectWithData: 的数据参数为 nil。 (这是错误)。也可以,NSData 对象是 nil。
标签: ios objective-c json parsing sentestingkit