Stephen
Stephen

Reputation: 3621

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.

Upvotes: 2

Views: 1111

Answers (2)

Johan Segerfeldt
Johan Segerfeldt

Reputation: 46

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

Upvotes: 2

nhgrif
nhgrif

Reputation: 62052

You could of course write a new function...

func assertLessThanOrEqual(value: Double, limit: Double) -> Bool {
    XCTAssertLessThanOrEqual(value, limit)
    return value <= limit
}

And then write your tests like...

var allGood = true
allGood = allGood && assertLessThanOrEqual(someComputedValue1, 0.5)
allGood = allGood && assertLessThanOrEqual(someComputedValue2, 0.2)

if !allGood {
    performAction()
}

Upvotes: 0

Related Questions