单元测试找不到核心数据模型文件
我创建了一个包含核心数据模型的项目。该应用程序查找模型文件 (.momd) 并运行良好。
不幸的是,单元测试不断返回 null:
NSURL *dataModelURL = [[NSBundle mainBundle] URLForResource:@"myDataModel" withExtension:@"momd"];
我可以在主目标和单元测试目标的编译源目录中看到 myDataModel.xdatamodeld 文件夹和文件 - 但这似乎还不够。我在单元测试目标中还缺少什么?
谢谢, ——路德
I've created a project with a Core Data model in it. The application looks for the model file (.momd) and runs just fine.
Unfortunately, the unit test keeps returning null:
NSURL *dataModelURL = [[NSBundle mainBundle] URLForResource:@"myDataModel" withExtension:@"momd"];
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?
Thanks,
-Luther
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不幸的是,单元测试目标不使用应用程序的主包,但它创建一个特殊的 UnitTest 包。因此,如果您需要在测试中使用捆绑资源(例如核心数据模型),则需要解决该问题。
最简单、最灵活的解决方法是在测试代码中使用
NSBundle
的bundleForClass:
方法。该方法的参数可以简单地由测试中的[self class]
给出。这样您就可以重用此代码,而无需在多个项目中调整包标识符。例子:
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.
The most simple and most flexible workaround would be using the
bundleForClass:
method ofNSBundle
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.Example:
答案与捆绑有关。单元测试目标不使用“主”包。它创建自己的包,在我的例子中,默认为“com.yourcompany.UnitTest” - 直接来自 [Target]-info.plist。
更正后的解决方案如下所示:
谢谢
The answer has to do with the bundle. A unit test target doesn't use the 'main' bundle. It creates its own bundle which, in my case, defaulted to 'com.yourcompany.UnitTest' - straight out of the [Target]-info.plist.
The corrected solution then looks like this:
Thanks
有类似的问题,我使用 OCMock 框架解决了它,所以我不需要更改应用程序代码
Had a similar problem, i solved it using the OCMock framework, so i did not need to change the application code
此方法将从任何目标获取您的包。但是,对于添加的每个目标,您必须手动将 plist 包标识符添加到
identifiers
数组中,因为无法以编程方式获取它。优点是您可以使用相同的代码来测试或运行应用程序。This method will get your bundle from any target. However, for each target you add, you have to manually add the plist bundle identifier to the
identifiers
array, because there is no way to get it programmatically. The advantage is that you can use the same code for testing or running the application.我的问题确实是错误的捆绑包!当我尝试使用框架中的数据库时,我“简单地”必须从相应的
Bundle
加载数据库!以下是 Swift4 中使用
MagicalRecord
的一些代码:瞧!
My problem was indeed the wrong Bundle! As I was trying to use a database from/within a Framework I 'simply' has to load the db from the corresponding
Bundle
!Here is some code in Swift4 using
MagicalRecord
:And voilà!