在 xcode 单元测试中加载文件 [英] Load files in xcode unit tests

查看:40
本文介绍了在 xcode 单元测试中加载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Xcode 5 单元测试项目和一些与之相关的测试 xml 文件.我尝试了很多方法,但似乎无法加载 xml 文件.

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.

我尝试了以下不起作用

NSData* nsData = [NSData dataWithContentsOfFile:@"TestResource/TestData.xml"];

NSString* fileString = [NSString stringWithContentsOfFile:@"TestData.xml" encoding:NSUTF8StringEncoding error:&error];

另外,如果我尝试使用 [NSBundle allBundles] 预览所有包,单元测试包没有出现在列表中?

Also if I try to preview all the bundles using [NSBundle allBundles] the unit test bundle does not appear in the list?

我尝试创建一个单独的资源包,但似乎无法以编程方式定位它,尽管它确实已构建和部署.

I tried to create a separate resource bundle and I can't seem to locate it programmatically although it does get built and deployed.

我做错了什么?

推荐答案

在运行测试时,应用程序包仍然是主包.您需要使用单元测试包.

When running tests the application bundle is still the main bundle. You need to use unit tests bundle.

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

这篇关于在 xcode 单元测试中加载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆