Skip to content

Is there a matcher that simultaneously asserts the type of an object and casts it? #923

@amomchilov

Description

@amomchilov
  • I have read CONTRIBUTING and have done my best to follow them.

I'm trying to make an assertion about the type of an error, and of a field on it. This requires me to cast.

This was my work-around:

expect(try somethingThatThrows()).to(throwError { error in
    expect(error).to(beAnInstanceOf(MyCustomError))
    expect((error as! MyCustomError).cause) == POSIXError(.ENOMEM)
}

Notice how I needed to force cast from Error to MyCustomError in order to gain access to the cause property. This force-cast shouldn't ever fail (because of the typecheck on the previous line), but it's still a little crufty.

Is there a build in matcher that can help with this?

Here are some other alternatives I considered:

expect(try somethingThatThrows()).to(throwError { error in
    if let error = error as? MyCustomError {
         expect(error.cause) == POSIXError(.ENOMEM)
    } else {
        fail()
    }
expect(try somethingThatThrows()).to(throwError { error in
    expect((error as? MyCustomError).cause) == POSIXError(.ENOMEM)
}

Environment

List the software versions you're using:

  • Quick: 4.0.0
  • Nimble: 9.2.0
  • Xcode Version: 13.0 (13A5201i)
  • Swift Version: 5.5

Please also mention which package manager you used and its version. Delete the
other package managers in this list:

  • Swift Package Manager 5.5.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions