2
votes

I've added a new target of type Cocoa Touch Unit Testing Bundle to an existing iOS project, a test case and some jpg files that I need for testing.

I'm trying to load the image from the test bundle using the following code :

@implementation PhotosViewController_Tests : XCTestCase

-(void)addImage:(NSString *)imageName
{
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    NSString *imagePath = [bundle pathForResource:imageName ofType:@"jpg"];
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];

    ...
}

However, bundle returns the main bundle, not the test bundle and imagePath and image are nil.

I can successfully load images from the main bundle (using this code), but I don't understand why bundleForClass returns the mainBundle instead of the unit test one.

I printed the [NSBundle allBundles] and I get the main bundle as well :

"NSBundle </var/mobile/Applications/uuid/Photos Light.app> (loaded)"

I guess it has something to do with adding the unit testing target after the project was created, but I can't figure what else to do to load images from the test bundle.

1

1 Answers

1
votes

Try adding an extension to NSBundle in your test target that looks something like this...

@implementation NSBundle (MyAppTests)

+ (NSBundle *)testBundle {
    // return the bundle which contains our test code
    return [NSBundle bundleWithIdentifier:@"com.mycompany.MyAppTests"];
}

@end

Then when you need to load resources from your test bundle, import that category and then your code looks like...

NSString *imagePath = [[NSBundle testBundle] pathForResource:imageName ofType:@"jpg"];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];