Load files in xcode unit tests

前端 未结 7 1893
失恋的感觉
失恋的感觉 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条回答
  •  -上瘾入骨i
    2021-02-02 06:05

    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)
    }
    

提交回复
热议问题