首页 > 解决方案 > 如何使用 Alamofire 和依赖注入构建适合测试的网络层?

问题描述

所以,我一直在尝试构建一个易于使用、维护和测试的网络层。我决定使用 Alamofire,因为它非常易于使用且易于维护(特别是在使用路由时)。

但是我一直卡在测试部分。原因如下:如何将基本 API url 注入路由器?我应该使用其他东西而不是路由模式吗?

下面我将留下一个UML图和部分代码。 UML 图

public protocol Router: URLRequestConvertible {
    var path: String { get }
    var method: HTTPMethod { get }
    var parameters: Parameters { get }
}

// this extension will provide a default implementation
// of the asURLRequest function
extension Router {
    public func asURLRequest() throws -> URLRequest {
        // my problem begins here, since I am using
        // a static/global reference for the base url
        let url = try BASE_URL.asURL()
        let request = try URLRequest(url: url.appendingPathComponent(path), method: method)
        guard !parameters.isEmpty else { return request }

        return try JSONEncoding.default.encode(request, with: parameters)
    }
}

非常感谢您的时间和帮助。

标签: iosswiftnetworkingalamofire

解决方案


推荐阅读