Search code examples
iosobjective-cxctest

Easiest way to use bundle resources for testing


Its convenient to use bundle resources for testing, for example to provide the expected outcome for a test.

For the old logic-style tests, I would use the main bundle for this, however for application style tests the main bundle is the app itself. I don't want to put test resources in the main bundle.

Eg, the following code is not working if the test resource only belongs to the test target:

//Load a resource from the main bundle
NSString* xml = [[JBBundleResource withName:@"signUpResponse.xml"] asString];

. . . is there a specific bundle for the tests? How can I get a handle to this?


Solution

  • Just use:

    NSBundle *testBundle = [NSBundle bundleForClass:[YourTestClass class]];
    

    or in Swift 3:

    let testBundle = Bundle(for: type(of: self))
    

    in tests code. Everything you add in 'Copy Bundle Resources' in 'Build Phases' for your Tests target in XCode will be available in this bundle.