I like to write unit tests. It gives me early feedback on my code and challenge my design. After all, unit tests are the first clients of my API.
Unit tests are cheap, easy to write, easy to maintain and fast to execute, at least they should 😆 Here I want to give just couple of tips on some setup within XCode.
Tip1: Naming and Folder
When writing Xcode projects I have folder structure which contains my code. I like to have the same folder structure under my unit test suites. It helps to keep things organised.
Also I follow this basic convention
- class A in my code → class ATests extends from XCTestCase to test all public methods of class A
- a function can be tested in multiple ways, it’s ok to have 3 or 4 unit tests testing the same functions with different parameters. It keeps things separated and easier to debug.
Tip2: Code Coverage
XCode offers test coverage to give early feedback on which part of your code is covered by unit tests.
⚠️ This doesn’t necessarily mean that your tests are good, but at least it can help you understand which part of your code is covered by unit tests or not.
You can enable as follow:
- Edit Scheme / Test / Options / Code Coverage
- Run the tests once more
- Go in Report Navigator
- Select your latest run and click on Coverage
- You can see all files parts of your project and if they are running during unit tests and how much the code is covered.
- Operation is 100% covered, and ArrayWithAtLeast2Items has not tests, so stays at 0%
On top, you can activate the Editor Options “Code Coverage” to see in your code, how much time a line of code is executed during unit tests.
Tip3: Randomize execution
Unit tests should not depend on each other. They should not depend on some kind of mutable states that are setup in your project, that you would need to reset to run another tests (Singleton for instance?)In theory they could run in any order independently.
There is a randomize option in XCode which will trigger the execution of your tests in randomized order.
- Go in Edit Scheme / Test / Info / Info / Randomize
Try it, you would be surprised to see some tests failing while activating this option.
This means possibly your code has potential vulnerabilities as well, or race conditions.
Thank you for reading until here… 👊 Have a good week end… 🍺