Cuckoo icon indicating copy to clipboard operation
Cuckoo copied to clipboard

'Generic parameter 'T' could not be inferred' when stubbing protocol with generics

Open seboslaw opened this issue 3 years ago • 5 comments

Hey guys,

I'm facing problems when setting up stubbing for the following protocol:

protocol KeyValueStorageProtocol {
    func load<T>(_ key: String, type: T.Type, completion: @escaping ((T) -> Void), failure: @escaping ((Error) -> Void)) where T: Codable
}

I'm currently saving Date objects in that Storage, so my test setup is as follows:

let mock = MockKeyValueStorageProtocol()
stub(mock) { stub in
  when(stub.load(any(), type: any(), completion: anyClosure(), failure: anyClosure()))
  .then({
    $2(Date())
  })
}

However, I'm getting the following error for the when(stub... line:

Generic parameter 'T' could not be inferred

So I'm not sure if providing the type (Date) in the .then command is enough to make the when(stub... resolve the generic type? I'm also not sure, I'm using the block syntax correctly here? I'm trying to make calls to the load function return a date in the completion block.

Any help or hints would be highly appreciated!

seboslaw avatar Oct 02 '21 21:10 seboslaw