Search code examples
swiftnsbundle

Swift - Get NSBundle for test target?


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")

Solution

  • 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.