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
Simply call the function, and assert against the return value:
func test_apple_withGoodBanana_shouldReturnBingCherry() throws {
let result = try apple(banana: goodBanana)
XCTAssertEqual(result, .bing)
}
By marking the test method itself as throws
we can call the try
without ?
or !
. If it throws, the test will fail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With