In one of my XCTests
classes, I need to load up an image from an asset catalogue to test an image processing logic. However, it seems like using UIImage(named: "imageName")
returns nil
in the testing target.
I checked the testing target membership in my Asset Catalogue, is there anything else I should do to enable reading of the image from my XCTest
classes?
An asset catalog is a type of file used to organize and manage different assets and image resolutions used by your app's user interface.
An asset catalog, simply put, is a single folder in Xcode that you use to organize your app's images, icons, colors, and more. Instead of adding individual images to Xcode's file organizer, you add assets neatly organized in a single catalog. Asset catalogs also include metadata, for example about image scale.
According to the documentation, you have to add them at runtime.
If your tests use assets—data files, images, and so forth—they can be added to the test bundle and accessed at run time using the NSBundle APIs. Using
+[NSBundle bundleForClass:]
with your test class ensures that you obtain the correct bundle to retrieve assets. For more information, see NSBundle Class Reference.
In Swift, it would be something along the lines of:
let appBundle = Bundle(for: type(of: MyClass) as! AnyClass)
The answer by @mylovemhz is correct but incomplete. You need to reference the bundle:
Swift 3:
UIImage(named: "imageName", in: Bundle(for: MyTestClass.self), compatibleWith: nil)
Also ensure that your asset is included in the same target as your test class.
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