Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a local json file in Xcode for unit test purposes?

So I have added the file testJson1.json to my project.

Within the unit test I have tried to get the filepath without any luck:

NSBundle *bundle = [NSBundle bundleForClass:[self class]];
NSString *filepath = [bundle pathForResource:@"testJson1.json" ofType:@"json"];

When I look at the project file, I can oddly enough see that the file is added to the resources, I thought unit test files would not be added to the resource to keep the app size down.

8AA238811C5565E80031648E /* testJson1.json in Resources */ = {isa = PBXBuildFile; fileRef = 8AA2387F1C5565E80031648E /* testJson1.json */; };

What am I missing please?

enter image description here

like image 745
Houman Avatar asked Jan 24 '16 20:01

Houman


People also ask

How do I run a local JSON file?

Chrome allows you to access local JSON or other data files if you launch it with the --allow-file-access-from-files flag. I checked this with the code above on version 34.0. 1847.131 m; it should work on other versions as well.

Where do I put JSON files in Xcode project?

To add the JSON file to your project, you can just drag and drop it inside Xcode: After adding the JSON file to your project, head to the ContentView. swift file. This is where we will read the JSON list and update the interface with our data.

How do I fetch local JSON in Swift?

if let path = Bundle. main. path(forResource: "assets/test", ofType: "json") { do { let data = try Data(contentsOf: URL(fileURLWithPath: path), options: . alwaysMapped) let jsonObj = try JSON(data: data) print("jsonData:\(jsonObj)") } catch let error { print("parse error: \(error.


2 Answers

Assuming you have a Test class from the above picture named...

final class TagNewsTests: XCTestCase {

In your func test() method load the bundle this way...

let url = Bundle(for: TagNewsTests.self).url(forResource: "testJson1", withExtension: "json")
like image 182
Waxhaw Avatar answered Sep 22 '22 10:09

Waxhaw


You just need to remove the .json from the resource name as this is not needed :)

NSString *filepath = [bundle pathForResource:@"testJson1" ofType:@"json"];

like image 43
ajfigueroa Avatar answered Sep 22 '22 10:09

ajfigueroa