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?
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 ✌️
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.
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
You could also use this (in Swift):
let bundle = NSBundle(forClass: MyClass.self)
let img = UIImage(named: "TestImage", inBundle: bundle, compatibleWithTraitCollection: nil)
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