Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moya stub request in BDD tests

I want to make a Moya stub request in my Quick/Nimble BDD tests. Moya has a sampleData parameter I created using a JSON file:

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
    }
}

How can I use this parameter in tests? Any ideas to make a Moya stub request in tests?

Thank you!

like image 418
Svyatoslav Avatar asked Feb 02 '17 00:02

Svyatoslav


2 Answers

Just use your provider like you did in your real code. Moya detects that current target is test target and will return the sample data instead of performing the request

like image 148
Javier Cancio Avatar answered Nov 15 '22 03:11

Javier Cancio


If you're still interested to use sample data for development (if backend is not ready yet), you can create Moya provider passing endpoint closure like below:

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)

It will return data, specified at public var sampleData: Data of TargetType protocol.

like image 33
Stanislau Baranouski Avatar answered Nov 15 '22 03:11

Stanislau Baranouski