Unit testing UIImageViews

Feb 9, 2013 13:20 · 181 words · 1 minute read bdd objectivec tdd testing

The scenario:

Your code updates a UIImageView, and you want to test that the change has taken place successfully.

The problem:

Once an image has been loaded into a UIImage object it becomes a cached binary representation with no metadata. You can’t ask a UIImage for the filename of the original image file. That makes testing difficult, and an image not being updated correctly is a high-impact problem.

The workaround:

The UIImageView class implements the UIAccessibility protocol that adds a accessibilityLabel property to any instances. This is read-write NSString which can be set as you load the image into the UIImageView:

UIImage *theImage = [UIImage imageNamed:@"kittens.png"];
  UIImageView *theImageView = [[UIImageView alloc] initWithImage:theImage];
  [theImageView setAccessibilityLabel:@"kittens"];

Once this accessibilityLabel property has been set, you can test it - here’s a Kiwi example:

[[[theImageView accessibilityValue] should] equal:@"kittens"];

And the equivalent SenTest syntax if you prefer the less-readable JUnit style:

STAssertEquals([theImageView accessibilityValue], @"kittens");

Assuming that you remember to update the accessibilityLabel property every time a UIImageView is updated, it’ll be possible to test that the change takes place correctly. Not perfect, but better than nothing.