cfischer
cfischer

Reputation: 24912

Test that a function does not throw an error

How can I assert that a function does not throw an error in Swift? In Objective C, there's an XCUnit macro for this case, but I can't find it in Swift.

Upvotes: 0

Views: 902

Answers (2)

rickster
rickster

Reputation: 126137

There's no specific XCTest function for this, but testing it yourself is pretty simple. Just write your own do/try/catch setup that XCTFails when an error is thrown, as in the developer forums link in @JAL's comment:

// generalized to a function
func AssertNoError(message: String = "", file: String = #file, line: UInt = #line, _ block: () throws -> ()) {  
    do { 
        try block() 
    } catch {  
        let msg = (message == "") ? "Tested block threw unexpected error." : message  
        XCTFail(msg, file: file, line: line)  
    }  
}  

// in use
AssertNoError(someVoidToVoidFunc)
AssertNoError("reason", { someFuncThatTakes(parameters) })

Upvotes: 3

mokagio
mokagio

Reputation: 17481

Along side @rickster's answer, if you are using the Nimble matcher, which I really recommend, you can write expectations like:

expect{ try somethingThatThrows() }.to(throwError())

expect{ try somethingThatShouldNotThrow() }.toNot(throwError())

Upvotes: 2

Related Questions