KVO Quick Spec unit tests

Swift Language


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


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.


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


Table of Contents

Using keyValueObservingExpectation will simplify your testing for KVO.


Table of Contents

Share These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Facebook
  • Twitter
  • LinkedIn
  • email
  • DZone
  • Slashdot
  • Reddit
  • Google Bookmarks
  • Digg
  • StumbleUpon
  • del.icio.us
This entry was posted in Swift, Testing, Uncategorized and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared.

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">