SwiftCheck icon indicating copy to clipboard operation
SwiftCheck copied to clipboard

Preferred idiom for testing exception-throwing code

Open jgongo opened this issue 6 years ago • 1 comments

Sorry if this is the wrong place to ask this... is there any preferred idiom for testing code that should throw an exception using SwiftCheck?

For example, I have the following pair of tests, and I'd like to make the second one less verbose if possible:

property("UInt values generate valid values") <- forAll { (number: UInt) -> Testable in
    return try! String(number).parseAsConditionalUInt(forElement: "element") == ConditionalUInt.uint(value: number)
}
property("Negative values cause exception") <- forAll { (number: Int) -> Testable in
    (number < 0) ==> {
        do {
            let _ = try String(number).parseAsConditionalUInt(forElement: "element")
            return false
        } catch {
            return error is ParseError<String>
        }
    }
}

jgongo avatar May 28 '18 12:05 jgongo

I've come up with the following in case anybody faces the same problem:

func errorThrownBy<T>(block: () throws -> T?) -> Error? {
    do {
        let _ = try block()
        return nil
    } catch {
        return error
    }
}
property("Negative values cause exception") <- forAll { (number: Int) in
    number < 0 ==>
        errorThrownBy { try String(number).parseAsConditionalUInt(forElement: "element") } is ParseError<String>
}

jgongo avatar May 28 '18 13:05 jgongo