xcodeunit-testingtestingmockingprotocols

XCode tests issue: 'any Protocol' does not conform to expected type 'Protocol' insert 'as! Protocol'


Started adding tests to supplementary objects

Tested class code:

class TokenAdapter {
   private let tokenProvider: TokenProviderProtocol!
   private let session: SessionProtocol!

   // MARK: - Init

   init(tokenProvider: TokenProviderProtocol, session: SessionProtocol) {
       self.tokenProvider = tokenProvider
       self.session = session
   }


protocol TokenProviderProtocol {
    func getToken(_ completion: @escaping (Result<String, Error>) -> Void)
}

protocol SessionProtocol {
    var isLoggedIn: Bool { get }
}

Tests code:

final class TokenAdapterTests: XCTestCase {
        
    func testUnauthorized() {
        ...
        
        let provider: TokenProviderProtocol = TokenProviderMocked()
        let session: SessionProtocol = SessionMocked(isLoggedIn: false)
        
        let adapter = TokenAdapter(tokenProvider: provider, session: session)
        ...
}

class TokenProviderMocked: TokenProviderProtocol {
    
    func getToken(_ completion: @escaping (Result<String, Error>) -> Void) {
        ...
    }
}

struct SessionMocked: SessionProtocol {
    private var _isLoggedIn: Bool
    
    init(isLoggedIn: Bool) {
        self._isLoggedIn = isLoggedIn
    }
    
    var isLoggedIn: Bool { _isLoggedIn }
}

In tests I'm getting next error on line let adapter = TokenAdapter(tokenProvider: tokenProvider, session: session):

"Argument type 'any TokenProviderProtocol does not conform to expected type 'TokenProviderProtocol' Insert ' as! TokenProviderProtocol'" enter image description here

If I do "fix", XCode adds as! TokenProviderProtocol like that:

...(tokenProvider: tokenProvider as! TokenProviderProtocol, ...

and 1) it changes nothing - error still there; 2) XCode now suggests to remove as! ... code enter image description here

Any ideas about the reason?


Solution

  • Found the reason and it was in absolutely not related to XCode's hints - File AccessTokenAdapter wasn't included in Tests target 😐

    P.S. So confused, that XCode didn't pointed that out 🤦‍♂️