CodeBender CodeBender - 26 days ago 8
Objective-C Question

Access an asset catalog for unit tests in Objective-C

I have a CocoaPods project written in Objective-C that I would like to run unit tests against. The project in question works with images, so I need to feed some images to it for testing purposes. Under no circumstances will these images be used in a release version - so they do not need to be accessible for the main target.

I started by creating an assets file & associated it with my test target:

enter image description here

Inside my assets file, I have created an entry for my first test image:

enter image description here

I have also verified that the assets file is being copied into the bundle resources under the test object project phases tab:

enter image description here

Then, in my unit test I call it:

- (void)testLoadImage {
UIImage *image = [UIImage imageNamed:@"colortestpattern"];
XCTAssertNotNil(image);
}


The test fails, as the image is not set.

Because I will need a large collection of images for testing, I was hoping to use the asset file. If however, this is not possible, then I'm open to alternatives.

Answer Source

Have you tried UIImage's class method imageNamed:inBundle:compatibleWithTraitCollection:?

UIImage *image = [UIImage imageNamed: @"colortestpattern"
                            inBundle: [NSBundle bundleForClass: [self class]]
       compatibleWithTraitCollection: nil];

The image should be in the unit test bundle, not the main bundle.