UI testing in a snap — iOSSnapshotTestCase
What Is It?
Previously known as FBSnapshotTestCase and currently maintained by Uber, this framework creates reference images of UIViews and uses them to test subsequent images of the same view to check that they are identical.
Why would I use it?
There are a couple of use cases I have found:
Writing UI in code
This is a big one for me. Within my team we have been moving away from xibs and Storyboards and creating all of our UI programtically.
One obvious downside of this is that you can’t see how the UI looks until you run the app.
Particularly in larger applications this can be cumbersome especially when the screen you want to view is nested deep within the navigation stack.
By using iOSSnapshotTestCase you can check the view by running the test and inspecting the reference image.
Nobody likes writing tests. There are many articles out there outlining the annoyances. I found creating tests with iOSSnapshotTestCase relatively simple.
After the Initial Setup, tests are created by subclassing FBSnapshotTestCase instead of XCTest.
recordMode = trueto allow reference image(s) to be generated when the test is ran.
Finally create a test that instantiates the view and call
Here’s an example:
Now that a reference image has been created, set
recordMode = false. Now if no changes have been made to the view the test will pass!
FBSnapshotVerifyView() there are several parameters that can be passed to offer more control. Such as the following:
FBSnapshotVerifyView(view, identitifer: "simpleView", tolerance: 0.5)
How does it work?
Underneath the hood, it compares views by rendering them into two CGContextRefs. Then it looks at the memory of them using the C function
memcmp() to make sure they are equal.
Since coming across this framework my workflow has simplified immensely. I work on a large application and having the ability to not compile and run the app every time I want to check out a UI changed has saved some significant time.
It’s a simple yet powerful tool that I would recommend people try out!