Skip to content

Handle generic completion handlers in mocked function #57

Open
@alschmut

Description

@alschmut

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions