Search code examples
swiftxctestxctestcase

How to check if an XCTestCase test has failed


Is it possible to check within a running test if any of its XCTAsserts have failed? I have a test with a few assertions in a row, and I want to add some code afterward to perform a specific action if any of them failed:

class testClass : XCTestCase
{
    func testSomething()
    {
        let someComputedValue1 = func1()
        let someComputedValue2 = func2()

        XCTAssertLessThanOrEqual(someComputedValue1, 0.5)
        XCTAssertLessThanOrEqual(someComputedValue2, 0.2)

        if anyOfTheAboveAssertionsFailed {
            performAction()
        }
    }
}

The part I'd like tips on is that anyOfTheAboveAssertionsFailed condition without duplicating the comparisons to the hard-coded values.


Solution

  • While using your own assertion methods solves the PO's issue, it is cumbersome if you need to use several XCAssert-methods.

    Another approach is to override continueAfterFailure. If there is no failure the property will not be requested. If there is one, it will.

    class MyTest: XCTest {
        private var hasFailed = false
        override var continueAfterFailure: Bool {
            get {
                hasFailed = true
                return super.continueAfterFailure
            }
            set {
                super.continueAfterFailure = newValue
            }
        }
        override func tearDown() {
            if hasFailed { performAction() }
            hasFailed = false
        }
    }