Search code examples
iosswiftxcodexctestxcuitest

How to test if a UIImageView contains an image with a specific name using XCUITest?


I have a collectionView that has a bunch of cells that contain a single UIImageView in each cell. I want to test wether or not in each cell, the imageView's image matches the correct image name.

In the production code, I've added an accessibility identifier to the UIImageView example: "My Image View". I loop through an array of strings containing image names and set the cell's image in accordance to the index, example: ["image0.png", "image1.png", "image2.png"] so cells at index 0-2 would have those images respectively.

In my XCUITest file I'm trying something like this:

XCTAssert(cells.images["My Image View"].exists, "message here")

But this doesn't check if the cell's imageView has the right image. Can anyone suggest a better solution?

Some references I visited beforehand:

How to test UIImageView elements in iOS XCTest?

XCUIElement - Obtain Image value

I apologize if this question has been asked before, I couldn't find anything.

Edit: I found a solution.

let image = cells.element(matching: , identifier: )

I didn't know that the identifier parameter actually uses the image name so If I pass the image name, I can assert the existence of the image.

let image = cells.element(matching: .image, identifier: "myImage.png")

this works. So when I loop through an array of strings containing the image name, I can also check if the cell at the index corresponding to the image index is correct.

I also forgot to mention that the images aren't being stored in assets, but are being fetched via json.

cesarmarch's answer below was the closest so I marked that as correct.


Solution

  • I just use something like

    XCTAssert(cells.images["Image_Name_In_Resource_Directory"].exists, "message here")

    to check if the current image is the good to use and it works fine.