Skip to content

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

Closed

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

Activity

  1. changed the title [-]Is there a matcher that simultaneously asserts the type of an object and casts?[/-] [+]Is there a matcher that simultaneously asserts the type of an object and casts it?[/+] on Aug 22, 2021
  2. ikesyo commented on Aug 28, 2021

    @ikesyo
    Member

    I think this overload is what you want.

    expect(try somethingThatThrows()).to(throwError(errorType: MyCustomError.self) { error in
        expect(error.cause) == POSIXError(.ENOMEM)
    }
  3. locked and limited conversation to collaborators on Aug 28, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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