Swift - 获取测试目标的NSBundle?

37

在 Objective C 中,每当我需要访问测试包时,我都会调用

[NSBundle bundleForClass:[ClassInTestTarget class]];

bundleForClass在Swift中不可用,那么我该如何访问测试包?

我需要这样做的原因是为了对我正在工作的框架编写测试,我必须使用内存中的core data stack。最初,所有资源都包含在主目标和测试目标中,但随后我将所有这些测试辅助程序移动到仅限于测试目标,现在下面的代码返回nil,导致我的所有测试失败。

let modelURL = NSBundle.mainBundle().URLForResource("Model", withExtension: "momd")
1个回答

62

相应的 Swift 代码为

// Swift 3 and later:
Bundle(for: ClassInTestTarget.self)

// Swift 1, 2:
NSBundle(forClass: ClassInTestTarget.self)

ClassInTestTarget.self返回“ClassInTestTarget”类的类对象。


这个有效:https://dev59.com/FmAf5IYBdhLWcg3wqEPp - Michael Ozeryansky
我已经在一些类中使其正常工作了,但在其他类中它返回了一个带有 /Applications/Xcode.app/Contents/Developer/usr/bin 路径的捆绑包。有什么想法为什么会这样,或者如何修复它? - Ian Bytchek
具体来说,这只会发生在泛型类中... - Ian Bytchek
1
在Swift 4.1中,Bundle(for: ClassInTestTarget.self)会导致错误Use of unresolved identifier 'ClassInTestTarget' - Reinhard Männer
3
@ReinhardMänner说,“ClassInTestTarget”是框架中某个类的占位符。您需要替换为现有类的具体名称,但不改变原意。 - Martin R
哦!我太蠢了,抱歉。我的问题是我想获取当前测试目标的捆绑包,这样我就可以在多个测试目标中使用代码。 - Reinhard Männer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接