ios – 如何读取本地JSON文件进行测试

前端之家收集整理的这篇文章主要介绍了ios – 如何读取本地JSON文件进行测试前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图为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可以获得单元测试类所在的包.
原文链接:https://www.f2er.com/iOS/330053.html

猜你在找的iOS相关文章