Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 737
Josh Paradroid Avatar asked Oct 01 '18 11:10

Josh Paradroid


1 Answers

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.

like image 54
Jon Reid Avatar answered Oct 08 '22 00:10

Jon Reid