如何读取本地JSON文件以进行测试 [英] How to read in a local JSON file for testing

查看:564
本文介绍了如何读取本地JSON文件以进行测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为json验证编写单元测试(因为app严重依赖于来自其余API的json)。

I'm trying to write unit tests for json validation (since the app heavily relies on json from a rest API).

我有一个本地文件包含简单的json:goodFeaturedJson.txt

I have a local file that contains simple 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 test fails every time. The console prints:

The json string is: (null)

为什么?我知道为什么测试失败,因为很明显,如果数据是nil / null,那么就没有有效的json,并且验证器将会中断(如果它无效则应该中断)。

Why? I know why the test is failing, since clearly if the data is nil/null there will be no valid json, and the validator will break (which it should if its invalid).

我必须在这里找到一些简单的东西,任何想法?

There must be something simple I missed here, any ideas?

推荐答案

在单元测试中你可能想要使用 [NSBundle bundleForClass:[self class]] ,而不是 [NSBundle mainBundle] 。那是因为单元测试不是一个独立的应用程序。使用 mainBundle ,您可以使用 /Applications/Xcode.app/Contents/Developer/Tools ,但使用 bundleForClass 获取单元测试类所在的包。

In a unit test you probably want to use [NSBundle bundleForClass:[self class]], and not [NSBundle mainBundle]. That's because the unit test is not a standalone app. With mainBundle you get something like /Applications/Xcode.app/Contents/Developer/Tools, but using bundleForClass gets you the bundle where your unit test class is located.

guard let pathString = Bundle(for: type(of: self)).path(forResource: "UnitTestData", ofType: "json") else {
    fatalError("UnitTestData.json not found")
}

这篇关于如何读取本地JSON文件以进行测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆