Swift - Get NSBundle for test target?

aryaxt picture aryaxt · Sep 1, 2014 · Viewed 11.7k times · Source

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

Answer

Martin R picture Martin R · Sep 1, 2014

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.