UIImage returns nil in UITests

640 views Asked by At

in my UITests I want compare image of element with the image from .xcassets:

 let referenceImage = UIImage(named: "referenceImage")
 guard  referenceImage != nil else {
    print("didn't find referenceImage image in assets")
    XCTAssert(false)
    return
    }
 let cellImage = myCell.images.elementBoundByIndex(0)
 let imagesEqual = (referenceImage!.isEqual(cellImage))
 XCTAssert(imagesEqual)

The referenceImage is always nil, although I've added Assets.xcassets to my UITests target (double checked in UITest target->Build phases/Copy bundle resources).

What can be wrong here?

1

There are 1 answers

1
Andrew On BEST ANSWER

UIImage uses the main bundle to look for the image. The test bundle is a different bundle. You should use UIImage's

init(named:in:compatibleWith:)

where you can specify your test bundle explicitly.

You can get the bundle for the test target with Bundle's initForClass , passing in your current test class.