【问题标题】:How to read in a local JSON file for testing如何读取本地 JSON 文件进行测试
【发布时间】: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


【解决方案1】:

在单元测试中,您可能希望使用[NSBundle bundleForClass:[self class]],而不是[NSBundle mainBundle]。那是因为单元测试不是一个独立的应用程序。使用mainBundle 你会得到类似/Applications/Xcode.app/Contents/Developer/Tools 的东西,但使用bundleForClass 会得到你的单元测试类所在的包。

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

【讨论】:

  • 该死,没有意识到关于 NSBundle 的事情;谢谢! (这解决了一切)。
【解决方案2】:

在 Swift 中

Swift 5 及以上版本

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

guard let jsonString = try? String(contentsOfFile: pathString, encoding: .utf8) else {
    fatalError("Unable to convert UnitTestData.json to String")
}

print("The JSON string is: \(jsonString)")

guard let jsonData = jsonString.data(using: .utf8) else {
    fatalError("Unable to convert UnitTestData.json to Data")
}

guard let jsonDictionary = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? [String:Any] else {
    fatalError("Unable to convert UnitTestData.json to JSON dictionary")
}

print("The JSON dictionary is: \(jsonDictionary)")

Swift 3 和 4

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

guard let jsonString = try? NSString(contentsOfFile: pathString, encoding: String.Encoding.utf8.rawValue) else {
    fatalError("Unable to convert UnitTestData.json to String")
}

print("The JSON string is: \(jsonString)")

guard let jsonData = jsonString.data(using: String.Encoding.utf8.rawValue) else {
    fatalError("Unable to convert UnitTestData.json to NSData")
}

guard let jsonDictionary = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? [String:AnyObject] else {
    fatalError("Unable to convert UnitTestData.json to JSON dictionary")
}

print("The JSON dictionary is: \(jsonDictionary)")

斯威夫特 2.2

    guard let pathString = NSBundle(forClass: self.dynamicType).pathForResource("UnitTestData", ofType: "json") else {
        fatalError("UnitTestData.json not found")
    }

    guard let jsonString = try? NSString(contentsOfFile: pathString, encoding: NSUTF8StringEncoding) else {
        fatalError("Unable to convert UnitTestData.json to String")
    }

    print("The JSON string is: \(jsonString)")

    guard let jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding) else {
        fatalError("Unable to convert UnitTestData.json to NSData")
    }

    guard let jsonDictionary = try? NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as? [String:AnyObject] else {
        fatalError("Unable to convert UnitTestData.json to JSON dictionary")
    }

    print("The JSON dictionary is: \(jsonDictionary)")

*这包含了 Tom Harrington 在 Objective C 中的答案

【讨论】:

  • 感谢您指出这一点:`Bundle(for: type(of: self))` 在其他任何地方都找不到它,这使它在单元测试中工作!
猜你喜欢
  • 2022-01-14
  • 1970-01-01
  • 2016-03-13
  • 1970-01-01
  • 1970-01-01
  • 2017-11-18
  • 2016-10-02
  • 2019-06-05
  • 2019-05-29
相关资源
最近更新 更多