rfodge rfodge - 1 year ago 127
Swift Question

How to run swift XCTest tearDown once

I am using xcode 8.3.3, swift, and I am trying to get the tearDown method to run only once.

I launch the application once with the solution provided here:
XCTestCase not launching application in setUp class method

In the tearDown method, I want to logout of the application. I only want to do this once.

The XCTest documentation has a class tearDown() method, but when I try to use it - it doesn't have access to the application anymore?:

This is all I get when I am in the tearDown method and so it can't access any elements on the application anymore:

enter image description here

How can I run the code in the tearDown just once at the end of all tests?

Answer Source

You can do something like this

class TestSuite: XCTestCase {

    static var testCount = 0
    static var amountOfTest = 0

    override class func setUp()
        amountOfTest = testInvocations.count

    override func setUp()

        TestSuite.testCount += 1

    override func tearDown()
        if TestSuite.testCount == TestSuite.amountOfTest {
            print("Final tearDown")


    func testA() {}
    func testB() {}
    func testC() {}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download