Normally, when we write unit tests in iOS, we usually use the
XCTAssert method to describe our expectation for the test. The syntax is very simple.
However, when these tests fail, we have no idea why.
Xcode only shows us
XCTAssertTrue failed or
XCTAssertFalse failed without any explanation.
Of course we can add a custom error message like this:
But this seems like an overkill.
Who’s gonna write error messages for every assertions? It’s gonna take ages.
Why don’t we just focus on writing whatever we expect and stop worrying about error messsages?
That’s where Nimble comes to the rescue
With Nimble, you can write your expectation just like plain English:
And when something fails, it shows exactly what went wrong:
If that is not clear enough (really?), you can still add your own error message:
There are a whole lot of useful Nimble methods that you can use to better desribe your expectation:
And so much more…
All available methods can be found on the Nimble’s documentation. There’s a section dedicated for Asynchronous Expectations which is extremely useful when you want to write tests for network requests. Please read if you want to fully utilize Nimble’s power.
So how do we install Nimble?
Just like any other pod, all you need to do is adding one single line
pod 'Nimble' to your Podfile. Note that since we only use Nimble for testing purpose, we want to add it to the test target only.
Terminal and type:
If you don’t know how to setup
cocoapods properly, you can read this post for detailed steps.
In this post, we discussed about some of
XCTAssert’s shortcomings and how
Nimble can fill that gap.
Nimble also provides an expressive way of writing your expectation so that it reads just like plain English. I highly recommend
Nimble to anyone who is learning to write unit tests and want to write them beautifully.