Including Asset Catalogue in Test Targets

3.5k views Asked by At

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?

2

There are 2 answers

0
mylovemhz On

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)
2
garie On

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.