Load files in xcode unit tests
When running tests the application bundle is still the main bundle. You need to use unit tests bundle.
Objective C:
NSBundle *bundle = [NSBundle bundleForClass:[self class]];NSString *path = [bundle pathForResource:@"TestData" ofType:@"xml"];NSData *xmlData = [NSData dataWithContentsOfFile:path];
Swift 2:
let bundle = NSBundle(forClass: self.dynamicType)let path = bundle.pathForResource("TestData", ofType: "xml")!let xmlData = NSData(contentsOfFile: path)
Swift 3 and up:
let bundle = Bundle(for: type(of: self))let path = bundle.path(forResource: "TestData", ofType: "xml")!let xmlData = NSData(contentsOfFile: path)
With swift Swift 3 the syntax self.dynamicType
has been deprecated, use this instead
let testBundle = Bundle(for: type(of: self))guard let ressourceURL = testBundle.url(forResource: "TestData", ofType: "xml") else { // file does not exist return}do { let ressourceData = try Data(contentsOf: ressourceURL)} catch let error { // some error occurred when reading the file}
or
guard let ressourceURL = testBundle.url(forResource: "TestData", withExtension: "xml")
As stated in this answer:
When the unit test harness runs your code, your unit test bundle is NOT the main bundle. Even though you are running tests, not your application, your application bundle is still the main bundle.
If you use following code, then your code will search the bundle that your unit test class is in, and everything will be fine.
Objective C:
NSBundle *bundle = [NSBundle bundleForClass:[self class]];NSString *path = [bundle pathForResource:@"TestData" ofType:@"xml"];NSData *xmlData = [NSData dataWithContentsOfFile:path];
Swift:
let bundle = NSBundle(forClass: self.dynamicType)if let path = bundle.pathForResource("TestData", ofType: "xml"){ let xmlData = NSData(contentsOfFile: path)}