Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load a test image for unit testing

I'm writing a test for a class that loads an image and does some color manipulation. The image is loaded with

    UIImage* image = [UIImage imageNamed:imageName];

If I run the app everything is fine and the images are loaded as expected. I added a unit test that shall use a specific test image to be loaded during the test. If I run the test fixture the image is not loaded. What I read so far is that the method imageNamed always loads from the app bundle's resource folder. How can I change this to the bundle of my test?

like image 550
trumi Avatar asked Aug 13 '12 20:08

trumi


4 Answers

In Swift 3.0 you would do:

let bundle = Bundle.init(for: NameOfYourTestClass.self)
let image = UIImage(named: "TestImage", in: bundle, compatibleWith: nil)

Where NameOfYourTestClass is the name of your test class ✌️

like image 168
Marijn Avatar answered Nov 18 '22 13:11

Marijn


If you mean that you have an image in the test bundle that you want to use only in tests (i.e. a test fixture), go have a look at this answer.

You can tailor that answer to get the NSBundle of your actual app by using [NSBundle bundleForClass:[SomeClassThatExistsInTheAppOnly class]]. This lets you specifically target the app bundle from a test bundle.

like image 35
Ryan McCuaig Avatar answered Nov 18 '22 13:11

Ryan McCuaig


Made a handy category for this.

image = [UIImage testImageNamed:@"image.png"];

Goes like:

@interface BundleLocator : NSObject
@end

@interface UIImage (Test)
+(UIImage*)testImageNamed:(NSString*) imageName;
@end

@implementation BundleLocator
@end

@implementation UIImage (Test)
+(UIImage*)testImageNamed:(NSString*) imageName
{
    NSBundle *bundle = [NSBundle bundleForClass:[BundleLocator class]];
    NSString *imagePath = [bundle pathForResource:imageName.stringByDeletingPathExtension ofType:imageName.pathExtension];
    return [UIImage imageWithContentsOfFile:imagePath];
}
@end
like image 5
Geri Borbás Avatar answered Nov 18 '22 12:11

Geri Borbás


You could also use this (in Swift):

let bundle = NSBundle(forClass: MyClass.self)
let img = UIImage(named: "TestImage", inBundle: bundle, compatibleWithTraitCollection: nil)
like image 3
Kevin Delord Avatar answered Nov 18 '22 13:11

Kevin Delord