Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 978
leedex Avatar asked Dec 31 '22 21:12

leedex


2 Answers

XCTest UI tests are designed to be written as functional tests, rather than checking that the display is correct. Since the image doesn't exhibit a behaviour for the UI test to observe, a UI test isn't the best tool for the job.

In this case, you should write unit tests to assert that the correct image is assigned to your image views, as unit tests will have access to the right level of information to allow you to inspect the data you pass to your view presentation layer and assert that the assigned image is the one you expect.

like image 53
Oletha Avatar answered Jan 03 '23 10:01

Oletha


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.

like image 42
cesarmarch Avatar answered Jan 03 '23 10:01

cesarmarch