Naming iOS Unit Test Methods

When writing code we come up with method or function names all the time. And it is pretty much up to us developers how to name our methods. When writing Unit Tests in Xcode there are a few little requirements for a test method name which we must follow if we want our test method to be executed. In this blog post, you will learn a few suggestions on how to name Unit Test methods in Xcode.

Unit Test Method Requirements

For a test method to execute it must follow the following requirements:

  • Each test method must begin with the prefix test,
  • Test method does not take arguments,
  • Test method does not return a value.

Below is an example of a unit test method name in Xcode.

func testColorIsRed() {
      
      // Some code here

}

Notice that:

  1. Method name starts with a prefix test,
  2. The method does not take arguments,
  3. And this method does not return any value.

If you rename this method to not contain the test prefix, this method will not execute and will be skipped.

The following method will not execute and will be skipped.

func skip_testColorIsRed() { 
   // Some code here 
}

Common Method Naming Convention

Although we are allowed to give our test methods any names we like(provided it starts with a test prefix) there is also a common naming convention that many(not all) iOS developers follow.

It is important to make a test method name descriptive and speak for itself. The goal is to understand what the test method is going to test just by looking at a method name rather than on the code it contains. So we try to make our test method names descriptive by following this pattern.

test<System Under Test>_<Condition Or State Change>_<Expected Result>()

Because of this pattern, test method names appear longer than usual method names but they are also very descriptive. Let’s have a look at an example of another test method name.

func testSignupFormModel_WhenInformationProvided_FirstNameShouldHaveValidLength() {
 
    // Some code here

}

Where

  • SignupFormModel is the name of a Model class that is under the test.

Another example:

func testSignupFormModel_WhenInformationProvided_PasswordsShouldMatch() {
 
}

Just by looking at the above test method name, we can figure out that:

  • We are testing a SignupForm Model class,
  • When the user provides their information,
  • Provided passwords should match.

I hope this short tutorial was of some value to you. There are other tutorials on Testing iOS Applications on this blog if you check the Unit Testing category.

Happy unit testing! 🙋🏻‍♂️

Leave a Reply

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