37

In Objective C whenever I had to access the test bundle I would call

[NSBundle bundleForClass:[ClassInTestTarget class]];

bundleForClass is not available in Swift, so how do I access the test bundle?

The reason I need this is that in order to write tests for a framework I'm working on I have to use an in memory core data stack. Initially all resources were included in both main target and test target, but then I moved all these test helpers to test target only, and now the code below is returning nil which fails all my tests

let modelURL = NSBundle.mainBundle().URLForResource("Model", withExtension: "momd")
Abizern
  • 146,289
  • 39
  • 203
  • 257
aryaxt
  • 76,198
  • 92
  • 293
  • 442

1 Answers1

62

The corresponding Swift code is

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

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

ClassInTestTarget.self return the class object for the "ClassInTestTarget" class.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • This works: http://stackoverflow.com/questions/24403718/swift-equivalent-objective-c-runtime-class – Michael Ozeryansky Jun 30 '15 at 22:38
  • I have this working in some classes, but in others it returns bundle with `/Applications/Xcode.app/Contents/Developer/usr/bin` path. Any ideas why / how to fix it? – Ian Bytchek Jun 27 '16 at 21:28
  • Specifically – only happens with generic classes… – Ian Bytchek Jun 27 '16 at 21:44
  • 1
    In Swift 4.1 `Bundle(for: ClassInTestTarget.self)` causes the error `Use of unresolved identifier 'ClassInTestTarget‘`. – Reinhard Männer Jun 19 '18 at 05:57
  • 3
    @ReinhardMänner: `ClassInTestTarget` is a *placeholder* for some class in the framework. You have to substitute the concrete name of an existing class. – Martin R Jun 19 '18 at 06:39
  • Oh! I am stupid, sorry. My problem is that I want to get the bundle for the **current** test target, so that I can use the code for several test targets. – Reinhard Männer Jun 19 '18 at 07:05