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
?
In XCTest you aren't in mainBundle. So get your image from your XCTest bundle.
(this solution is for iOS8+)
[UIImage imageNamed:@"..." inBundle:[NSBundle bundleForClass:[self class]] compatibleWithTraitCollection:nil];
UIImage(named: "...", in: Bundle(for: type(of: self)), compatibleWith: nil)
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
It works fine for me with the same code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With