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

编程入门 行业动态 更新时间:2024-10-24 12:27:32
本文介绍了如何读取本地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文件以进行测试

本文发布于:2023-11-24 09:13:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1624612.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:进行测试   文件   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!