TDD In Practise

When it comes to Testing In Swift, there are 3 keys,

1 – Design your code for clear testability.

Unified Input & Output: In the functional programming world there is this talk about pure function which simply means that same input will always produce the same output no matter where it is called. You don’t have to become Haskell programmers and change all your code according to pure functionality, yet, you may want to inspire by them to make your code easier to test.

Keep Our State Local: In the Apple Community a lot of people are using singleton patters simply because they are used to. We have seen Apple do it like, UIScreen, UIDevice, Bundle, etc. So we as IOS Devs, tend to use it by default even when we really don’t need it. As singletons can be nice for sharing some apis they can also lead you a dangerous paths such as undefined state. So before using it we must think that whether we really need it or not. In summary, my humble suggestion would be try to keep states in local so that we are gonna end up with less bugs and also easier to test the code.

Dependency Injection: When you are testing a state or functionality, all the needs to create output must be declared as you call the testing function, so try not to put variables in the class itself but try to create them while calling the function via putting those variables in initializers. So that, all the needs will always generate the same output with the same input no matter when or where.

2 – Remember that you are going to write a test against all your public api. So keep caution on access modifiers.

Always keep going with framework oriented programming, so that your codes will be easy to test and easy to reuse them.

3 – We all need mocks when it comes to testing, yet be very careful while using them. Remember your only purpose is writing tests to check your real code. Mocks come with a cost and more complexity. And you can end up instead of testing your api, testing too much of your implementation.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s