Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preferred idiom for testing exception-throwing code #271

Open
jgongo opened this issue May 28, 2018 · 1 comment
Open

Preferred idiom for testing exception-throwing code #271

jgongo opened this issue May 28, 2018 · 1 comment

Comments

@jgongo
Copy link

jgongo commented May 28, 2018

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 jgongo changed the title Preferred idiom for testing exception throwing code Preferred idiom for testing exception-throwing code May 28, 2018
@jgongo
Copy link
Author

jgongo commented May 28, 2018

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant