Part 2: Getting our hands dirty with code!

This is the Part 2 of the post: Making friends with TDD!

The part which I love the most!

So let’s get started with developing the right thought for TDD!

The thought behind TDD is to write the test first and then the code to make it pass! Generally, we end up doing it the other way round.

Let’s discuss the use cases in hand. We have a Sign Up page, which has a password field. The use cases talk about the various validations to be added to a password field.

There are major five requirements for validation:

  1. The password must be at least 8 characters long.
  2. There must be at least one capital case letter type.
  3. There must be at least one lower case letter type.
  4. There must be at least one special character type.
  5. There must be at least one numerical character type.

The aforementioned cases must be fully satisfied in order to let a password pass. As we are going to use TDD as the development approach, we’ll be writing the test cases first.

Let us head straight to Xcode!

Using the project that we created in part 1 of this series of posts.

Now, you have an option to delete the MakingFriendsWithTDDTests.swift file. You may delete it or may use it for writing the tests. Personally, I like to create more specific files i.e. files and classes with more specific names and purposes. It’s your call.

For those who want to have a new file with a more specific name, I’ll show how to create a new one!

Head to the Project Navigator section and right click on the MakingFriendsWithTDDTests folder.

Click on the New File… option. Or you may just press ⌘ + N. By performing either of options you’ll be greeted with the following screens. Take reference and proceed on the same grounds.

The steps mentioned are quite simple and self-explanatory. For the last one, you may choose “Don’t Create” option, as the project is going to be just in Swift for now.

Lazy ones, Rejoice! You may download the starter project here: MFW_TDD_Starter

Before writing a test method, first let us understand a test method/case:

Basic attributes of a Test Method/Case:

The basic attributes of a test method:

  • Test method name should always have a prefix as “test”. If you don’t add this you won’t able to run it like a test.
  • You cannot have parameters supplied to a test method.
  • A test method’s purpose is to verify/exercise the content provided inside it and to report failures using a set of assertion APIs.
  • Since a test reports failure using assertion APIs, the purpose of having a return value is lost.
  • One needs to import the corresponding header files of classes which you wish to test in the test class.

That’s pretty much it when it comes to test methods. The aforementioned points must be adhered to in order to make a test method work.

When you create your first test case class, you will see four methods, setUp,  tearDown,   testExample and testPerformanceExample. Out these four may discard the testExample and testPerformanceExample methods. These are meant for examples and have no specific purpose.

The setUp and tearDown are not mandatorily required but are important when you have something common to write in the test class across contained test cases. ThesetUp method is called before the invocation of each test case in the class and the tearDown is called after the invocation of each test case in the class. So some common stuff as in instantiating a testable class etc can be done in the setUp method. Any action which needs to be performed after the test methods execute can be done in the tearDownmethod.

Having seen the test class and test method basicswe can now jump to writing some test methods and playing around with some code!

Now we are looking to write our first test case which will verify the length of the entered text for us. How to do it? Simple, check the string for the number of characters. Let’s take a look.

XCTAssertEqual, is a test assertionthis macro takes two parameters. If they turn out to be equal, great! but if not it fails.

The test case we’ve written is bound to fail! The string length is surely under 8 characters! See, that’s the purpose! In TDD you are required to write the very basic form of code that is required for verifying or implement a requirement.

In order to test a single test case, you may click the small diamond shaped mark showing across the method’s signature.

Or press ⌘ + U to run the test case! It will return a false-positive and would look something like,

Let’s try to make this test succeed.

Voilà, our first test has passed!

Next to the code of our first test case, you should see a green tick. Isn’t it just gorgeous!

This also explains how the XCTAssertEqual works. It compares both the parameters and asserts only when both match. This helps a lot in comparing booleans. There are a bunch of asserts available, here.

The test case we just wrote does not feel correct, does it?

Nay! There is something wrong with this! What if I have to test two or three string lengths, all at once? I’ll have to copy the same lines of code to all the tests. Shouldn’t it be more generic?

Let’s do it then! Let us follow single responsibility principle and create an “Authenticator” class. Its job would be to validate various inputs. Let’s begin then!

Go ahead and create a new class in a new swift file, following the same steps discussed earlier.

The one I created looks something like this! I just moved the code from the AuthenticationTests class’ method testPasswordLength method to new class’ method. Rather than verifying locally defined strings, I have just changed the method to accept a string which needs to be verified.

Let us now update the Authentication class’ method.

If you get an error similar to the one shown above, you can follow the following steps:

  • Add @testable import MakingFriendsWithTDD above the AuthenticationTests class. This makes the module testable and available inside the test file.
  • If done, clean the code by pressing ⌘ + SHIFT + K. The error would be gone!

With the error gone, run the test again! Do you see the green tick? Yay! It worked. (Keeping our emotions in control, let’s move ahead!)

Now with the latest success, you may add more tests! Tests to verify various other strings. Take this as a challenge and try and do it by yourself. Use the comments section below to place your solutions.

Did you do it? If yes, you might be able to see one line getting repeated!

If your answer is a “Yes”! Let’s make some changes and use the setUpmethod now.

This is how the class looks now. The  authenticator variable has been changed to a class property and an optional. The  authenticator has been initialized in the setUpmethod, as the setUpmethod is called before all the test methods, the initialized value is accessible by all the test methods and we can safely use the defined optional.

Further, the code written in the Authenticator class can be modified and be made a bit more generic.

P.S. There is no correct way writing a method, it’s just the way you like it to be. Keep in mind the basics of programming though!

There are few more conditions to be met. I’ll leave it to you to write those.

  • The password must be at least 8 characters long.
  • There must be at least one capital case letter type.
  • There must be at least one lower case letter type.
  • There must be at least one special character type.
  • There must be at least one numerical character type.

Give it a try by writing different test methods and then following it by writing the required methods in the Authenticator class. (Hint: Use Regular Expressions)

I would also insist on providing the results in the comments below.

I feel a bit magnanimous today! 🙂 In case you need to check all the cases in a single method you may use Regular Expressions. Refer the below code (Spoiler Alert!)

You may download the project here, MFW_TDD_Part_1_Complete.



Do you feel like a “Boss” now?





Thanks for reading through this! Hope this acted as the initial ice-breaker between you and TDD!

Do let me know if this was helpful. Also, let me know if you are looking for posts on anything else as in Regular Expressions etc.

Keep an eye out for the next in line, Firebase Integration with network testing and UI Testing!

Until next time, Adios!

Peace ✌

Please follow and like us:

Leave a Reply

Your email address will not be published. Required fields are marked *