Test UserDefaults

Now we’re ready to use our fake object to test the app. Let’s start by adding a test suite ViewControllerTests. Use Test Zero as temporary scaffolding to confirm that you hooked up the test suite. (See Start from Test Zero.) Delete Test Zero once you see its expected failure message.

For our first test case, let’s test viewDidLoad. That method gets the integer for the key "count" from userDefaults and stores this in the count property. The didSet observer on that property takes the count and updates the counter label. These are the things we’ll test. (It also happens to write the count back to userDefaults, which is a little wasteful but not a big deal. It’s not a requirement, so we shouldn’t test it.) To invoke viewDidLoad ...

Get iOS Unit Testing by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.