May 2, 2017

Swift Mock Objects: How to Avoid Fragile Tests

Click to play

3  comments

I've written about my experience of going to try! Swift Tokyo 2017. Now thanks to the video and transcript provided by Realm, I can also share the talk I gave: "Making Mock Objects More Useful."

I start by showing the basics of how to make a Swift mock object by hand. But this easily leads to fragile tests because the assertions are overspecified. We need ways to make tests more malleable, with mocks that are more flexible.

Code snippet sample

Improve your test writing “Flow.”

Sign up to get my test-oriented code snippets.

You can also read the written transcript of my talk.

Playback speed: Native English speakers may want to increase the playback speed of the video. Because there was simultaneous interpreting, I spoke very slowly, with unusually crisp enunciation. So I was happy when an attendee tweeted in Japanese, "Thanks to the slow speaking style, I could listen without the interpreter for the first time!"

Equality Assertions Can Be Too Strong

One of my points in the talk is to avoid overusing equality. This is something I've addressed before, outside of Swift mock objects. See Let's Stop Overusing Swift Equatables in Unit Tests.

Making mock objects by hand easily leads to fragile tests because the assertions are overspecified.

Click to Tweet

Swift Mock Objects Sample Code

When I kept referring to my own sample code for my day job, that gave me a good feeling. If this talk was useful for my own work, I knew it would help others, too. I still check it to remind myself how to write mock objects in Swift!

CLICK HERE to download the Swift Mock Objects​ code.

Do you have any questions about mock objects in Swift? Please share in the comments below.

Revealing Hidden Objects: Can DDD Improve Your Code?

Jon Reid

About the author

Programming was fun when I was a kid. But working in Silicon Valley, I saw poor code lead to fear, with real human costs. Looking for ways to make my life better, I learned about Extreme Programming, including unit testing, test-driven development (TDD), and refactoring. Programming became fun again! I've now been doing TDD in Apple environments for 20 years. I'm committed to software crafting as a discipline, hoping we can all reach greater effectiveness and joy. Now a coach with Industrial Logic!

  • I tried to download the sample project, but none of my email addresses worked. It stated “An error occurred while submitting your data. Please try again”.
    I guess more testing is necessary ?

  • {"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

    Never miss a good story!

    Want to make sure you get notified when I release my next article or video? Then sign up here to subscribe to my newsletter. Plus, you’ll get access to the test-oriented code snippets I use every day!

    >