seanhenry / SwiftMockGeneratorForXcode

An Xcode extension (plugin) to generate Swift test doubles automatically.
MIT License
751 stars 48 forks source link

Handle generic completion handlers in mocked function #57

Open alschmut opened 2 years ago

alschmut commented 2 years ago

The below mocked generic completion handler does not compile as the generic Value can not be found outside the function.

Current state:

protocol MyProtocol {
    func foo<Value: Codable>(completion: (Value) -> Void)
}

class MyProtocolMock: MyProtocol {

    var invokedFoo = false
    var invokedFooCount = 0
    var stubbedFooCompletionResult: (Value, Void)? // Value can not be found

    func foo<Value: Codable>(completion: (Value) -> Void) {
        invokedFoo = true
        invokedFooCount += 1
        if let result = stubbedFooCompletionResult {
            completion(result.0)
        }
    }
}

Proposed solution:

protocol MyProtocol {
    func foo<Value: Codable>(completion: (Value) -> Void)
}

class MyProtocolMock: MyProtocol {

    var invokedFoo = false
    var invokedFooCount = 0
    var stubbedFooCompletionResult: (Any, Void)? // Change Value to Any

    func foo<Value: Codable>(completion: (Value) -> Void) {
        invokedFoo = true
        invokedFooCount += 1
        if let result = stubbedFooCompletionResult {
            completion(result.0 as! Value) // Force cast as Value
        }
    }
}

Ideally the solution also covers more complex completion handlers, where the generic type is nested. E.x:

func foo<Value: Codable>(completion: (Result<Value, Never>) -> Void)