The Order of Unit Tests in Xcode

Unit tests in Xcode can run in different orders. They can run in alphabetical order, randomized or executed in parallel. The default order in which Xcode runs unit tests is alphabetical. In this blog post, you will learn how the alphabetical order works.

The Flow of Unit Test Execution

For each test method, a new instance of the class is allocated and its instance setup method executed. For each test method, XCTest will execute the setUp() method first, then, a next test method in alphabetical(default) order and then the tearDown() method. So the sequence is the following:

  1. setUp()
  2. testMethod()
  3. tearDown()

Alphabetical Order (Default order)

By default, Xcode runs Unit Tests in alphabetical order. To demonstrate this I will create a new test class with 4 different test methods in it and run them to see their order of execution.

  • testA(),
  • testB(),
  • testC(),
  • testD()
import XCTest
@testable import OrderOfUnitTestsTutorial

class OrderOfUnitTestsTutorialTests: XCTestCase {
 
    override func setUp() {
        print("\n")
        print("setUp")
    }

    override func tearDown() {
        print("Tear down")
        print("\n")
    }

    func testA() {
        print("Running Test A")
    }

    func testB() {
        print("Running Test B")
    }
    
    func testC() {
        print("Running Test C")
    }
    
    func testD() {
        print("Running Test D")
    }

}

The output will be the following:

setUp
Running Test A
Tear down
setUp
Running Test B
Tear down
setUp
Running Test C
Tear down
setUp
Running Test D
Tear down

As you can see test methods did run in alphabetical order. For each test method, Xcode executed the setup() method first, then the next test method in alphabetical order and finally the tearDown() method.

Reorder Test Methods And Run Again

Let’s change the order of test methods and run tests again.

import XCTest
@testable import OrderOfUnitTestsTutorial

class OrderOfUnitTestsTutorialTests: XCTestCase {
    
    override func setUp() {
        print("\n")
        print("setUp")
    }
    
    override func tearDown() {
        print("Tear down")
        print("\n")
    }

    func testD() {
        print("Running Test D")
    }
    
    
    func testC() {
        print("Running Test C")
    }
    
    func testB() {
        print("Running Test B")
    }
    
    func testA() {
        print("Running Test A")
    }
    
}

If I run these test methods now I will get the following result.

setUp
Running Test A
Tear down
setUp
Running Test B
Tear down
setUp
Running Test C
Tear down
setUp
Running Test D
Tear down

As you can see, all test methods were executed in alphabetical order even we have reordered them from top to bottom.

Xcode Unit Test Execution Flow

Happy unit testing! 🙋🏻‍♂️

Leave a Reply

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