Load files in xcode unit tests

前端 未结 7 1887
失恋的感觉
失恋的感觉 2021-02-02 05:17

I have an Xcode 5 unit test project and some test xml files related to it. I\'ve tried a bunch of approaches but I can\'t seem to load the xml files.

I\'ve tried the fol

7条回答
  •  清酒与你
    2021-02-02 05:47

    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) 
    

提交回复
热议问题