我试图为json验证写单元测试(因为应用程序大量依赖于来自休息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,并且验证器将会中断(如果它的无效则应该是这样).
有没有什么简单的我想念的任何想法?
解决方法
在单元测试中,你可能想使用[NSBundle bundleForClass:[self class]],而不是[NSBundle mainBundle].这是因为单元测试不是独立的应用程序.使用mainBundle,您可以获得/Applications/Xcode.app/Contents/Developer/Tools,但是使用bundleForClass可以获得单元测试类所在的包.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。