Search code examples
unit-testingassertxctest

How do I get the returning value of a function that can throw that I'm testing with XCTAssertNoThrow(...)


I want to get the return value of a function that I'm testing for a subsequent test. The function if defined like this:

func apple(banana: Banana) throws -> Cherry { ... }

I can test that it throws when it should:

XCTAssertThrowsError(try apple(banana: badBanana), "Didn't throw")

I can test it doesn't throw when it shouldn't:

XCTAssertNoThrow(try apple(banana: goodBanana), "Did throw")

I was hoping to do this:

XCTAssertNoThrow(let cherry = try apple(banana: goodBanana), "Did throw")

and then check cherry is what I would expect, but I get the following error: Consecutive statements on a line must be separated by ';'...

How can I get the returned value (an object of type Cherry in this case) from the XCTAssertNoThrow test? Or is there a better approach that I'm missing?

Many thanks


Solution

  • Here's one I like better; it doesn't cause testing to halt just because an unexpected error gets thrown. And it lets you add a message:

    func CheckNoThrow<T>(
      _ expression: @autoclosure () throws -> T,
      _ message: @autoclosure () -> String = "",
      file: StaticString = (#filePath),
      line: UInt = #line
    ) -> T? {
      var r: T?
      XCTAssertNoThrow(
        try { r = try expression() }(), message(), file: file, line: line)
      return r
    }