Trying out ApprovalTests for iOS.
What is ApprovalTests and its process? Why? How to get started? How to migrate your existing unit test? Final Thoughts.
It is a testing tool to simplify testing assertions, by allowing you to compare a snapshot of your SUT. This tool also helps to quickly add a verification assertion like “ApprovalTests.verify(myObject)”, and continue creating your production code without thinking about your assertion beforehand.
”A picture’s worth a 1000 tests.”
It is used for many languages, including Swift for iOS developers.
Process:
Create your test assertion using “ApprovalTests.verify(myObject)”.
Run the tests. On each test run, the ApprovalTests framework will output two files, a “received” and an “approval” file. The first one will output the current description of the object in text, the second output file will be the desired description of the tested object.
Update the “approval” file as you progress in the production file using a diff tool (e.g. DiffMerge).
Repeat the 2, and 3 steps until you’re satisfied with the outcome.
Why?
This comes in handy if you want to quickly verify your System Under Test Object (SUT) so that you don’t have to think about the assertion upfront (e.g., ApprovalTests.verify(mySUT)). The “verification” compares the SUT's “current” description and the SUT's “approved” description.
How to get started?
It is very easy to get started. I’d use Swift Package Manager in this example, but you can also use Carthage or CocoaPods.
1) Add a package with the link https://github.com/approvals/ApprovalTests.Swift and use the master branch.
2) Make sure to add the package to your Test Target
3) Install DiffMerge. https://sourcegear.com/diffmerge/downloads.html.
How to migrate your existing unit test?
1) Import the ApprovalTests_swift framework.
2) Add conformance to “CustomStringConvertible” to your SUT’s type.
3) Replace your XCTAssertions with “Approvals.verify(sut)” method.
4) Update your approval file if needed. And Make your test pass.
When the test passes, the framework will automatically remove the received file.
Before
After
Finally, Don’t forget to git ignore the received files!
Help out a fellow iOS developer by subscribing to this substack and clicking the “subscribe now” button below. It will be much appreciated.
Final Thoughts.
I believe it is very easy to get started and it’s easy to use. Maybe it’s a little too early to be used in production code since there are a couple of things to be improved, like the ability to get blazing-fast feedback, but certainly, it can be used as an experiment in a pet project.
Finally, try it for yourself! And let me know what you think.
Would you like to learn more? Follow Jon Reid’s Videos on ApprovalTests https://qualitycoding.org/approvaltests-swift-getting-started/