Download a test image for unit testing

I am writing a test for a class that loads an image and does some color manipulation. Image is uploaded using

UIImage* image = [UIImage imageNamed:imageName]; 

If I run the application, everything will be fine and the images will load as expected. I added a unit test, which should use a specific test image to load during the test. If I run the test device, the image will not be uploaded. So far, I read that the imageNamed method is always loaded from the application resource folder. How can I change this to a bunch of my test?

+7
source share
6 answers

Made a convenient category for this.

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

Looks 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 
+4
source

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 ✌️

+4
source

If you mean that you have an image in a test suite that you want to use only in tests (i.e. a test device), go to this answer .

You can customize this answer to get the NSBundle of your real application using [NSBundle bundleForClass:[SomeClassThatExistsInTheAppOnly class]] . This allows you to configure the target application package from a test package.

+2
source

You can also use this (in Swift):

 let bundle = NSBundle(forClass: MyClass.self) let img = UIImage(named: "TestImage", inBundle: bundle, compatibleWithTraitCollection: nil) 
+1
source

well, one option would be to add this resource to your test (application).

personally, I just use paths ( initWithContentsOfFile: , data ( initWithData: , etc. this may include the introduction of several parameters - but this is good in many cases because this parameter can be used to test more input image files (if you want) without changing / cloning / repackaging the application.

0
source

To change a set of applications:

let bundle = Bundle (ID: "org.cocoapods.ACSPLib")

let photo = UIImage (name: nameofThePhoto, in: bundle, compatibleWith: nil)

bundle identifier

package identifier for module

0
source

All Articles