KVO Quick Spec unit tests

Swift Language

Swift

If you’re using KVO, how can you test the changes on your classes/structs?

Introduction

Table of Contents

Quick tests can still use the expectations you’ve used via XCTest. So let’s start there.

Let’s start with a very simple class with one dynamic property – remember, to use KVO it needs to be marked dynamic and the class needs to subclass NSObject.

Now here’s a QuickSpec to test it.
I do the usual add/remove observer chacha along with the required callback (observeValue), set up an expectation then fulfill it in the callback. If there is a timeout, the test fails.

keyValueObservingExpectation

Table of Contents

That works. But what a pain. Great if you’re paid by LOC.
Luckily, there is an expectation – keyValueObservingExpectation – just for KVO. You don’t need to add/remove observers and “manually” fulfill expectations.

Here is an example.

Or even better, since you’re just testing a value, you can use this version:

Here is the much simpler full example:

Groovy, huh?

Table of Contents

Summary

Table of Contents

Using keyValueObservingExpectation will simplify your testing for KVO.

Resources

Table of Contents

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.