单元测试无法找到Core Data模型文件 [英] Unit Test can't find Core Data model file
问题描述
我已经创建了一个包含Core Data模型的项目。应用程序查找模型文件(.momd)并运行正常。
I've created a project with a Core Data model in it. The application looks for the model file (.momd) and runs just fine.
不幸的是,单元测试一直返回null:
Unfortunately, the unit test keeps returning null:
NSURL *dataModelURL = [[NSBundle mainBundle] URLForResource:@"myDataModel" withExtension:@"momd"];
我可以在主目标和单元测试目标的编译中看到myDataModel.xdatamodeld文件夹和文件源目录 - 但这似乎不够。我在单元测试目标中还缺少什么?
I can see the myDataModel.xdatamodeld folder and file in BOTH the main target and the unit testing target's Compile Sources directory - but that doesn't seem to be enough. What else am I missing in the unit test target?
谢谢,
-Luther
Thanks, -Luther
推荐答案
不幸的是,单元测试目标不使用应用程序的主bundle,但它会创建一个特殊的UnitTest-bundle。因此,如果您需要在测试中使用捆绑资源(如核心数据模型),则需要解决该问题。
Unfortunately, a unit test target does not use the application's main bundle but it creates a special UnitTest-bundle. So if you need to use bundled resources (like a Core Data model) within your tests, you need to work around that issue.
最简单,最灵活的解决方法是在测试代码中使用 bundle $ C> c> NSBundle
的 bundleForClass:
方法。该方法的参数可以简单地通过测试中的 [self class]
给出。这样您就可以重用此代码而无需在多个项目中调整包标识符。
The most simple and most flexible workaround would be using the bundleForClass:
method of NSBundle
within your testing code. The parameter for that method can simply be given by [self class]
within your tests. That way you can reuse this code without having to adjust the bundle identifiers in multiple projects.
示例:
- (void)testBundleLocation
{
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
NSURL *url = [bundle URLForResource:@"myDataModel" withExtension:@"momd"];
...
}
这篇关于单元测试无法找到Core Data模型文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!