danielsaidi / MockingKit

MockingKit is a Swift SDK that lets you easily mock protocols and classes in `Swift`.
MIT License
87 stars 7 forks source link

suggestion: introduce hasCalled(_, with:) #19

Open 0xWOF opened 1 year ago

0xWOF commented 1 year ago

Hello, thank you for building awesome project. I suggest that adding hasCalled(_, with:) to support verify mock function is called with specific argument. I think it is very common usecase and it would be very helpful to users. If you okay with suggestion 1 or suggestion 2, I'll happy to create pull request. Thanks!

suggestion 1

implementation

func hasCalled<Argument0, Argument1, Result>(
    _ ref: MockReference<(Argument0, Argument1), Result>,
    with arguments: (Argument0, Argument1)
) -> Bool where Argument0: Equatable, Argument1: Equatable {
    calls(to: ref).first {
        $0.arguments.0 == arguments.0
        && $0.arguments.1 == arguments.1
    } != nil
}

func hasCalled<Argument0, Argument1, Argument2, Result>(
    _ ref: MockReference<(Argument0, Argument1, Argument2), Result>,
    with arguments: (Argument0, Argument1, Argument2)
) -> Bool where Argument0: Equatable, Argument1: Equatable, Argument2: Equatable {
    calls(to: ref).first {
        $0.arguments.0 == arguments.0
        && $0.arguments.1 == arguments.1
        && $0.arguments.2 == arguments.2
    } != nil
}

usage

XCTAssertTrue(mock.hasCalled(mock.functionWithVoidResultRef, with: ("abc", 456)))

suggestion 2

implementation

func hasCalled<Arguments, Result>(
    _ ref: MockReference<Arguments, Result>,
    with check: (Arguments) -> Bool
) -> Bool {
    calls(to: ref).first { check($0.arguments) } != nil
}

usage

XCTAssertTrue(mock.hasCalled(mock.functionWithVoidResultRef, with: { $0 == ("abc", 456) }))
danielsaidi commented 1 year ago

Hi @0xWOF

That's a great suggestion, thank you! I'd love to have that in the library 👍

I like approach 1, but it would be nice to have a single function for it.

Give me some time to ponder this, and I'll get back to you.