在xcodeunit testing中加载文件

我有一个xCode5unit testing项目和一些与之相关的testingxml文件。 我已经尝试了一堆方法,但我似乎无法加载XML文件。

我已经尝试了以下不起作用

NSData* nsData = [NSData dataWithContentsOfFile:@"TestResource/TestData.xml"]; NSString* fileString = [NSString stringWithContentsOfFile:@"TestData.xml" encoding:NSUTF8StringEncoding error:&error]; 

另外,如果我尝试使用[NSBundle allBundles]预览所有的捆绑包,unit testing包不会出现在列表中?

我试图创build一个单独的资源包,我似乎无法编程find它,虽然它得到build立和部署。

我究竟做错了什么 ?

运行testing时,应用程序包仍然是主包。 你需要使用unit testing包。

目标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:

 let bundle = Bundle(for: type(of: self)) let path = bundle.path(forResource: "TestData", ofType: "xml")! let xmlData = NSData(contentsOfFile: path) 

正如在这个答案中所述 :

当unit testing工具运行你的代码时,你的unit testing包不是主包。 即使你正在运行testing,而不是你的应用程序,你的应用程序包仍然是主要的包。

如果你使用下面的代码,那么你的代码将search你的unit testing类所在的包,并且一切都会好的。

目标C:

 NSBundle *bundle = [NSBundle bundleForClass:[self class]]; NSString *path = [bundle pathForResource:@"TestData" ofType:@"xml"]; NSData *xmlData = [NSData dataWithContentsOfFile:path]; 

迅速:

 let bundle = NSBundle(forClass: self.dynamicType) if let path = bundle.pathForResource("TestData", ofType: "xml") { let xmlData = NSData(contentsOfFile: path) } 

使用Swift Swift 3,语法self.dynamicType已被弃用,请使用它

 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 } 

要么

 guard let ressourceURL = testBundle.url(forResource: "TestData", withExtension: "xml") 

相对path是相对于当前工作目录。 默认情况下,这是/ – 根目录。 它正在您的启动磁盘的根目录下查找该文件夹。

获取捆绑中的资源的正确方法是向您的捆绑软件寻求帮助。

在一个应用程序中,你可以使用[NSBundle mainBundle]获得这个包。 我不知道这是否在testing案例中起作用。 尝试它,如果它不(如果它返回nil或一个无用的捆绑对象),replace[NSBundle bundleForClass:[self class]]

无论哪种方式,一旦你有了这个包,你可以问它为资源的path或URL。 除非你有一个非常具体的理由需要一个path(比如使用NSTask将它传递给命令行工具),否则通常应该使用URL。 发送包的URLForResource:withExtension:消息来获取资源的URL。

然后,为了从中读取一个string,使用[NSString stringWithContentsOfURL:encoding:error:] ,传递你从bundle中获取的URL。