无法将类型'MyEnum <t.type>'的值转换为预期的参数类型'MyEnum <_>'

时间:2019-01-29 15:25:12

标签: swift unit-testing generics

我有一个使用泛型的网络层,并且正在使用协议,以便稍后进行测试。我已遵循本教程https://medium.com/thecocoapps/network-layer-in-swift-4-0-972bf2ea5033

这是我的模拟测试:

import Foundation
@testable import TraktTest

class MockUrlSessionProvider: ProviderProtocol {

    enum Mode {
        case success
        case empty
        case fail
    }

    private var mode: Mode

    init(mode: Mode) {
        self.mode = mode
    }

    func request<T>(type: T.Type, service: ServiceProtocol, completion: @escaping (NetworkResponse<T>) -> Void) where T: Decodable {                
        switch mode {
        case .success: completion(NetworkResponse.success(T))
        case .empty: completion(.failure(.noData))
        case .fail: completion(.failure(.unknown("Error")))
        }

    }
}

此行出现错误:Cannot convert value of type 'NetworkResponse<T.Type>' to expected argument type 'NetworkResponse<_>':completion(NetworkResponse.success(T))

如果将其发送给完成成功,它将进行编译: try? JSONDecoder().decode(T.self, from: data!) (我使用编码和模型创建的虚拟数据),但进入模型时会崩溃,因为尽管我已经使用JSONEncoder()对正确的模型进行了编码,但还是无效。

我认为它是可行的,因为在我的类中使用了与我的应用中实现ProviderProtocol相同的逻辑:

final class URLSessionProvider: ProviderProtocol {

    private var session: URLSessionProtocol

    init(session: URLSessionProtocol = URLSession.shared) {
        self.session = session
    }

    func request<T>(type: T.Type, service: ServiceProtocol, completion: @escaping (NetworkResponse<T>) -> Void) where T: Decodable {
        let request = URLRequest(service: service)
        session.dataTask(request: request) { [weak self]  data, response, error in
            let httpResponse = response as? HTTPURLResponse
            self?.handleDataResponse(data: data, response: httpResponse, error: error, completion: completion)
        }.resume()
    }

    private func handleDataResponse<T: Decodable>(data: Data?, response: HTTPURLResponse?, error: Error?, completion: (NetworkResponse<T>) -> Void) {
        guard error == nil else { return completion(.failure(.unknown(error?.localizedDescription ?? "Error"))) }
        guard let response = response else { return completion(.failure(.unknown("no_response".localized()))) }

        switch response.statusCode {
        case 200...299:
            guard let data = data, let model = try? JSONDecoder().decode(T.self, from: data) else { return completion(.failure(.noData)) }
            completion(.success(model))
        default: completion(.failure(.unknown("no_response".localized())))
        }
    }

}

URLSessionProtocol只是一种协议,其方法dataTask与URLSession.shared中的方法相同(接收URLRequest并在完成时返回Data,Response和Error)。

“我的网络”回复是几个枚举:

enum NetworkResponse<T> {
    case success(T)
    case failure(NetworkError)
}

enum NetworkError {
    case unknown(String)
    case noData
}

我的提供程序协议仅具有使用泛型发出请求的功能:

protocol ProviderProtocol {
    func request<T>(type: T.Type, service: ServiceProtocol, completion: @escaping(NetworkResponse<T>) -> Void) where T: Decodable
}

我认为我不需要在测试中使用ServiceProtocol,因为它是使用端点,标头,正文,id等设置请求的。但这是我创建的协议:

typealias Headers = [String: String]
typealias Parameters = [String: Any]

protocol ServiceProtocol {
    func baseURL() -> URL
    var path: String? { get }
    var id: String? { get }
    var method: HTTPMethod { get }
    var task: Task { get }
    var headers: Headers? { get }
    var parametersEncoding: ParametersEncoding { get }
}

enum HTTPMethod: String {
    case get = "GET"
    case post = "POST"
}

enum Task {
    case requestPlain
    case requestParameters(Parameters)
}

enum ParametersEncoding {
    case url
    case json
}

在我的应用中,我有一个实现ProviderProtocol的类,并在某些viewModel用适当的模型调用请求时使用URLSession.shared来创建dataTask。

我经常使用协议和特定模型进行测试,但使用泛型向我显示该错误。如何实现使用泛型的模拟提供程序,以便可以测试使用不同类型的模型(存根)进行网络调用的任何viewModel。

1 个答案:

答案 0 :(得分:1)

发生错误是因为NetworkResponse需要T的实例,而模拟程序试图提供实际的T

因此,您需要以某种方式提供一个实例,但是该实例无法由模拟生成,因为它没有有关如何构造实例的足够信息。

我建议在创建模拟时从外部注入成功值。您可以通过使模拟类通用或使Mode枚举通用来实现。下面是后者的示例实现:

class MockUrlSessionProvider: ProviderProtocol {

    // making the enum generic, to support injecting the success value
    enum Mode<T> {
        case success(T)
        case empty
        case fail
    }

    // need to have this as `Any` to cover all possible T generic arguments
    private var mode: Any

    // however the initializer can be very specific
    init<T>(mode: Mode<T>) {
        self.mode = mode
    }

    func request<T>(type: T.Type, service: ServiceProtocol, completion: @escaping (NetworkResponse<T>) -> Void) where T: Decodable {
        // if the mock was not properly configured, do nothing
        guard let mode = mode as? Mode<T> else { return }
        // alternatively you force cast and have the unit test crash, this should help catching early configuration issues
        // let mode = mode as! Mode<T>

        switch mode {
        case let .success(value): completion(NetworkResponse.success(value))
        case .empty: completion(.failure(.noData))
        case .fail: completion(.failure(.unknown("Error")))
        }

    }
}