Unit Test can't find Core Data model file Unit Test can't find Core Data model file xcode xcode

Unit Test can't find Core Data model file


Unfortunately, a unit test target does not use the application's main bundle but it creates a special UnitTest-bundle. So if you need to use bundled resources (like a Core Data model) within your tests, you need to work around that issue.

The most simple and most flexible workaround would be using the bundleForClass: method of NSBundle within your testing code. The parameter for that method can simply be given by [self class] within your tests. That way you can reuse this code without having to adjust the bundle identifiers in multiple projects.

Example:

- (void)testBundleLocation{    NSBundle *bundle = [NSBundle bundleForClass:[self class]];    NSURL *url = [bundle URLForResource:@"myDataModel" withExtension:@"momd"];    ...}


The answer has to do with the bundle. A unit test target doesn't use the 'main' bundle. It creates its own bundle which, in my case, defaulted to 'com.yourcompany.UnitTest' - straight out of the [Target]-info.plist.

The corrected solution then looks like this:

NSBundle *bundle = [NSBundle bundleWithIdentifier:@"com.yourcompany.UnitTests"];NSURL *url = [bundle URLForResource:@"myDataModel" withExtension:@"momd"];

Thanks


Had a similar problem, i solved it using the OCMock framework, so i did not need to change the application code

@interface TestCase()    @property (nonatomic, strong) id bundleMock;@end@implementation TestCase- (void)setUp{    self.bundleMock = [OCMockObject mockForClass:[NSBundle class]];    [[[self.bundleMock stub] andReturn:[NSBundle bundleForClass:[self class]]] mainBundle];    [super setUp];}- (void)tearDown{    [self.bundleMock stopMocking];    [super tearDown];}