SwiftMockGeneratorForXcode
SwiftMockGeneratorForXcode copied to clipboard
Handle generic completion handlers in mocked function
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)