BDD 测试中的 Moya 存根请求

Moya stub request in BDD tests

我想让 Moya stub request in my Quick/Nimble BDD tests. Moya 有一个 sampleData 参数,我使用 JSON 文件创建:

var sampleData: Data {
    switch self {
    case .getPlaces:
        // Provided that project have a file named get_places.json in it's bundle.
        guard let path = Bundle.main.path(forResource: "get_places", ofType: "json"),
            let data = Data(base64Encoded: path) else {
                return Data()
        }
        return data
    case .getPlaceDetail:
        // Provided that project have a file named get_place_detail.json in it's bundle.
        guard let path = Bundle.main.path(forResource: "get_place_detail", ofType: "json"),
            let data = Data(base64Encoded: path) else {
                return Data()
        }
        return data
    }
}

如何在测试中使用这个参数?在测试中提出 Moya 存根请求有什么想法吗?

谢谢!

就像在真实代码中一样使用您的提供程序。 Moya检测到当前目标是测试目标,将return样本数据而不是执行请求

如果您仍然对使用示例数据进行开发感兴趣(如果后端尚未准备好),您可以通过 endpoint 闭包创建 Moya 提供程序,如下所示:

let endpoint = { (target: NetworkApiService) -> Endpoint in
            return Endpoint(url: URL(target: target).absoluteString,
                            sampleResponseClosure: { .networkResponse(200, target.sampleData) },
                            method: target.method,
                            task: target.task,
                            httpHeaderFields: target.headers)
        }
let provider = MoyaProvider<NetworkApiService>(endpointClosure: endpoint, stubClosure: MoyaProvider.immediatelyStub)

它将 return 数据,在 TargetType 协议的 public var sampleData: Data 指定。