Quick / Nimble

A Matcher Framework for Swift and Objective-C
https://quick.github.io/Nimble/documentation/nimble/
Apache License 2.0
4.79k stars 595 forks source link

Add a `require` function, similar to `expect`, which either returns the expression if it passes, or throws if it fails. #1102

Closed younata closed 6 months ago

younata commented 7 months ago

Taking some inspiration from swift-testing, I like the idea of the #require macro, and feel it would be a really good idea to bring to Nimble.

The basic idea is to replace a lot of setup code that looks like:

func setUp() {
    expect(nillableExpression()).toEventuallyNot(beNil())
    guard let value = nillableExpression() else { return }
    // ...
}
// or
func setUp() {
    expect(someObject.value).toEventually(equal(expectedValue))
    guard someObject.value == expectedValue else { return }
    // ...
}

with something like this:

func setUp() throws {
    let value = try require(nillableExpression()).toEventuallyNot(beNil())
    // ...
}

The require DSL would have a signature similar to expect, only to/toNot/toEventually/etc. would either throw or return the value of the expression.

Bonus: This also gets Nimble functionality similar to XCTUnwrap, which we have been lacking. Admittedly, try expect(someExpression()).toNot(beNil()) is MUCH more verbose than try XCTUnwrap(someExpression()). I think we should ship an unwrap function which essentially calls require(arg).toNot(beNil()). We do a similar thing with the fail matcher. Similarly, we should also ship a simple function for require(arg).toEventuallyNot(beNil()).