2

I understand that a class is a blueprint of a future object and I'm attempting to get a better grasp of OOP architecture using Swift. So the question I have is, what is the process that happens when you run your tests from a class and instances perspective. I don't think I've actually created an instance of my XCTestCase subclass necessarily but Xcode seems to do this automatically. As I'm building more passion project apps, I usually have to create an instance in order to use it but in testing I don't get that feeling and it just works by hitting (Command + U). I'd like to understand if an instance is even create at all and if so how?

Here's some sample code of a blueprint XCTestCase subclass but I never have to actually instantiate this class:

import XCTest
@testable import FirstDemo

class FirstDemoTests: XCTestCase {

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }

    func testExample() {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
    }

    func testPerformanceExample() {
        // This is an example of a performance test case.
        self.measure {
            // Put the code you want to measure the time of here.
        }
    }

}
Laurence Wingo
  • 3,912
  • 7
  • 33
  • 61

2 Answers2

1

The XCTestCase classes are instantiated in the same way as all other classes.

Its just that they are created in a separate process and everything is managed by the XCTest framework, either you run all tests and all classes related to the test target are instantiated, or you pick separate tests and separate classes are instantiated.

You can investigate the XCTest source code here: https://github.com/apple/swift-corelibs-xctest

Community
  • 1
  • 1
Oleh Zayats
  • 2,423
  • 1
  • 16
  • 26
1

When you run your app, your code is not responsible for creating the app delegate: the UIKit framework takes on this responsibility.

Similarly, when you run your tests, the test runner takes responsibility for instantiating your test cases. It discovers them by searching the list of all loaded classes for those that are a kind of XCTestCase. Then it asks each class for its test invocations. Then it can create test case instances for those test methods and run the tests.

Key to how this works is the rich metadata that the Objective-C runtime provides and the metaprogramming interfaces it offers to interrogate and manipulate that information.

Jeremy W. Sherman
  • 35,901
  • 5
  • 77
  • 111