【问题标题】:What should I include in my network mocking function?我应该在我的网络模拟功能中包含什么?
【发布时间】:2019-01-16 16:50:14
【问题描述】:

我想测试我的网络请求代码。测试不是我的强项,我这样做主要是为了更好地创建可测试的代码。我通常使用 Alamofire,但想绕过它进行单元测试。我创建了一个这样的协议:

protocol NetworkSession {
    func request(
        _ endpoint: Endpoint,
        method: HTTPMethod,
        completion: @escaping (Result<<DataResponse<Any>>, RequestError>) -> ()
    )
}

我在课堂上遵守此协议NetworkSessionManager:

final class NetworkSessionManager : NetworkSession {
    func request(
        _ endpoint: Endpoint,
        method: HTTPMethod,
        completion: @escaping (Result<<DataResponse<Any>>, RequestError>) -> ()) {
        guard let url = endpoint.url else {
            return completion(.failure(.couldNotEncode))
        }
        Alamofire.request(url, method: method, headers: headers)
            .validate()
            .responseJSON { response in

                completion(.success(response))
            }
        }
    }
}

然后在我的BackendClient 类中注入并调用我的NetworkSessionManager,如下所示:

private let session: NetworkSession

init(session: NetworkSession = NetworkSessionManager()) {
    self.session = session
}


func someFunction(...) {
    session.request(...)
}

现在我知道我需要创建一个符合NetworkSession 的模拟类,但我不确定我应该在其中做什么?如何测试所有可能性和返回的数据?我的服务器上有不同的端点返回不同类型的数据。如果有人能指出我应该采取的下一步措施,我将不胜感激。

final class NetworkSessionManagerMock : NetworkSession {
    func request(
        _ endpoint: Endpoint,
        method: HTTPMethod,
        completion: @escaping (Result<<DataResponse<Any>>, RequestError>) -> ()) {
        ???
    }
}

【问题讨论】:

    标签: ios swift unit-testing


    【解决方案1】:

    我将展示两个示例,希望它们可以帮助您开始模拟您的 NetworkSession。

    不过,首先,您可以向模拟类添加其他属性,以支持注入值来测试各种情况。我现在将演示错误情况和返回。

    enum MyError: Swift.Error {
        case failed
    }
    
    final class NetworkSessionManagerMock : NetworkSession {
        var myError: MyError?
        var dataResponse: Any? // This should hopefully be typed to something
    
        func request(
            _ endpoint: Endpoint,
            method: HTTPMethod,
            completion: @escaping (Result<<DataResponse<Any>>, RequestError>) -> ()) { [weak self] in 
            if let myError = self?.myError {
                // Send error with completion handler
            } else if let dataResponse = self?.dataResponse {
                // Send data response
            }
        }
    }
    

    这里的想法是您在测试中实例化模拟,然后根据需要设置变量以测试相应的部分。然后您的模拟将正常进行。

    我没有测试这段代码的语法正确性,所以如果有错误请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-18
      • 1970-01-01
      • 2011-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多