Frage

I can't get XCTestCase unit tests for a Cocoa Touch Static Library which rely on code that uses imageNamed to work.

I added my image "plane.png" to the test target, but [UIImage imageNamed] keeps returning nil.
When I explicitly specify the path of the image in the test and load the image from file it does work.

NSString* imagePath = [[[NSBundle bundleForClass:[self class]] resourcePath] stringByAppendingPathComponent:@"plane.png"];
UIImage* imageWorks = [UIImage imageWithContentsOfFile:imagePath];

UIImage* imageStaysNil = [UIImage imageNamed:@"plane.png"];

How can I write unit tests for code that uses imageNamed?

War es hilfreich?

Lösung

In XCTest you aren't in mainBundle. So get your image from your XCTest bundle.

(this solution is for iOS8+)

ObjC

[UIImage imageNamed:@"..." inBundle:[NSBundle bundleForClass:[self class]] compatibleWithTraitCollection:nil];

Swift

UIImage(named: "...", in: Bundle(for: type(of: self)), compatibleWith: nil)

Andere Tipps

The accepted answer didn't work for me; here's what did.

let image = UIImage(contentsOfFile: 
    Bundle(for: type(of: self))
    .path(forResource: "plane", ofType: "png")!)!

Since your xctest project acts like different project It's mandatory to add your .png file for xctest also.

add your plane.png image to xctest project also. Make sure you have checked like

enter image description here

It works fine for me with the same code

enter image description here

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top