Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including Asset Catalogue in Test Targets

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?

like image 840
Enrico Susatyo Avatar asked Dec 20 '16 05:12

Enrico Susatyo


People also ask

What is an asset catalog?

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.

What is asset catalog Xcode?

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.


2 Answers

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)
like image 56
mylovemhz Avatar answered Oct 17 '22 05:10

mylovemhz


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.

like image 24
garie Avatar answered Oct 17 '22 06:10

garie