为什么不能在单元测试内部代码找到bundle资源? [英] Why can't code inside unit tests find bundle resources?

查看:279
本文介绍了为什么不能在单元测试内部代码找到bundle资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有些代码我单元测试需要加载一个资源文件。它包含以下行:

Some code I am unit testing needs to load a resource file. It contains the following line:

NSString *path = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"txt"];

在应用程序中它运行正常,但是当单元测试框架运行 pathForResource:返回nil,表示找不到 foo.txt

In the app it runs just fine, but when run by the unit testing framework pathForResource: returns nil, meaning it could not locate foo.txt.

我已经确保 foo.txt 包含在单元测试目标的复制捆绑资源构建阶段中,所以为什么不能找到文件

I've made sure that foo.txt is included in the Copy Bundle Resources build phase of the unit test target, so why can't it find the file?

推荐答案

当单元测试工具运行你的代码时,你的单元测试包是 NOT 主包。

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. (Presumably, this prevents the code you are testing from searching the wrong bundle.) Thus, if you add a resource file to the unit test bundle, you won't find it if search the main bundle. If you replace the above line with:

NSBundle *bundle = [NSBundle bundleForClass:[self class]];
NSString *path = [bundle pathForResource:@"foo" ofType:@"txt"];

然后你的代码将搜索你的单元测试类所在的包,一切都会好。

Then your code will search the bundle that your unit test class is in, and everything will be fine.

这篇关于为什么不能在单元测试内部代码找到bundle资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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