Including Asset Catalogue in Test Targets
Asked Answered
D

2

16

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?

Dad answered 20/12, 2016 at 5:8 Comment(0)
M
16

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.

Misdemean answered 25/4, 2017 at 2:1 Comment(2)
I'm having trouble getting similar functionality to work with NSImage (macOS).Jenness
Are you able to transfer this answer also to an objective-c one?Handmedown
C
3

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)
Cutting answered 12/1, 2017 at 16:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.