Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include a file in Test Bundle swift?

I have json file that I want to include in the test bundle so I can just read this json for my tests.

So I created a file called "test.json", it is in my Tests folder.

Now I want to read this file. I am reading it like this, the code here is in the test file in test bundle:

 let bundle = Bundle(for: type(of: self))
 var url = bundle.url(forResource: "test", withExtension: "json")

the url is nil every single time. I swear that file is there, if I open it in finder, it's under the same directory as the test-info.plist. I even tried the main bundle but it is still nil!!

Where is this file????

like image 707
Anna Avatar asked Dec 08 '25 09:12

Anna


1 Answers

Try this:

let bundle = Bundle(for: YourTestClass.self)
let path = bundle.path(forResource: "test", ofType: "json")
let data = try Data(contentsOf: URL(fileURLWithPath: path))
like image 187
Adam Bardon Avatar answered Dec 10 '25 23:12

Adam Bardon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!