1

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?: https://developer.apple.com/documentation/xctest/xctestcase/understanding_setup_and_teardown_for_test_methods

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?

reutsey
  • 1,743
  • 1
  • 17
  • 36

2 Answers2

5

You can do something like this

import XCTest

class TestSuite: XCTestCase {

    static var testCount = testInvocations.count

    override func setUp()
    {
        super.setUp()

        TestSuite.testCount -= 1
    }

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

        super.tearDown()
    }

    func testA() {}
    func testB() {}
    func testC() {}
}
Titouan de Bailleul
  • 12,920
  • 11
  • 66
  • 121
  • Thank you! This workaround will do for now :) I really wish apple would provide overall test setUp and tearDown methods that work like they say they do! The only change I needed to do was use "self.testInvocations().count" instead of "testInvocations.count" – reutsey Jul 27 '17 at 16:00
  • I don't think you need the `self` part but the `()` might still be needed in swift 3. – Titouan de Bailleul Jul 28 '17 at 02:27
1

XCTestCase has two different setUp/tearDown combinations. One is at the individual test case level. The other is at the suite level. Just override the class versions to get the entire suite:

override class func setUp() {
    super.setUp()
    // Your code goes here
}

override class func tearDown() {
    // Your code goes here
    super.tearDown()
}
Jon Reid
  • 20,545
  • 2
  • 64
  • 95