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

I am going through an excellent book on Test Development in Swift. My ultimate goal is to better understand OOP architecture. When I read the book, it says early in the section that the setUp () method is run before each test method, which I understand is setting up the objects to run the test to fail or fail. I'm not sure how much this is possible, I'm guessing this is an architecture point of view? How was Apple able to create a class that has a method that runs before any other method in the class?

Here's 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.
        }
    }

}

      

+3


source to share


3 answers


I think the class XCTest

has a lifecycle like like UIViewController

.

The same as viewDidLoad()

called after init(coder:)

when the view is loaded into memory, the method is also called setUp()

after the test class is loaded (once during the lifetime of the object).

You can also explore the source code of source and third-party test frameworks on github:



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

https://github.com/google/googletest

+4


source


You will subclass a class called XCTestCase. Typically Testframework looks at the classes that define test methods and run them in a specific order.

Anyway, im not 100% sure if XCTest works this way, but you can try looking at the source code and try to dig deeper there:



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

+2


source


For each test under test: setup()

called, then the actual test, then teardown()

.

Then set up another test from that class again and tearDown again ... until all ** tests in your test class have run.

The sequence of lines will not affect which test is called first.

The reason this is done is because the 2 tests must be 100% independent. You don't want testExample to do anything for the / sut / system _under_test object (mutate its state) that you run your tests on, but don't override it. Otherwise, your testPerformanceExample will be loaded from a state you weren't expecting.

+2


source







All Articles