Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the setUp() method called before the invocation of each test method?

I'm going through a great book learning about test-driven development in Swift. My ultimate goal is to get a better understanding of OOP architecture. As I'm reading the book, a section early on states that the setUp() method is fired before each test method which I understand does the setup of objects to run the test for a pass or fail result. What I'm unsure of is how is this even possible I'm guessing from an architecture stand-point? How was Apple able to make a class that has a method which is fired before every other method in the class?

Here is some sample code:

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.
        }
    }

}
like image 676
Laurence Wingo Avatar asked Jan 05 '23 05:01

Laurence Wingo


2 Answers

I think XCTest class has a lifecycle just like UIViewController for example.

Same as viewDidLoad() called after init(coder:) when the view is loaded into memory, setUp() method is also called after the test class is loaded (once during the life of the object).

You can also investigate native and third party test frameworks source code on github:

https://github.com/apple/swift-corelibs-xctest

https://github.com/google/googletest

like image 58
Oleh Zayats Avatar answered Jan 06 '23 19:01

Oleh Zayats


You are Subclassing a Class called XCTestCase. Usally Testframework introspects Classes in which Test-Methods are defined and run them in a particular order.

Anyway, im not 100% sure if the XCTest is working this way, but you could try to have a look at the source code and try to dig deeper there:

https://github.com/apple/swift-corelibs-xctest

like image 39
Kris Avatar answered Jan 06 '23 18:01

Kris