我正在尝试为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文件以进行测试
发布评论