Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using UIImage imageNamed inside XCTestCase

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?

like image 554
Pieter Avatar asked Apr 07 '14 07:04

Pieter


3 Answers

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)
like image 83
Cœur Avatar answered Oct 19 '22 01:10

Cœur


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")!)!
like image 34
ratbum Avatar answered Oct 19 '22 01:10

ratbum


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

like image 24
Rajesh Avatar answered Oct 19 '22 01:10

Rajesh