Moya stub request in BDD tests
Asked Answered
K

2

10

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!

Kautz answered 2/2, 2017 at 0:12 Comment(0)
C
13

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

Clite answered 3/2, 2017 at 15:10 Comment(2)
I'm trying to write a test which checks a response from getPlaces request, but following both tests is successful for this response: testProvider.request(.getPlaces(location: "")) { places in expect(places).to(beNil()) } and testProvider.request(.getPlaces(location: "")) { places in expect(places).toNot(beNil()) }. Why this happens? What I'm doing wrong?Kautz
Did you create your test provider using stubClosure? Like this let provider = RxMoyaProvider<YourTargetType>(stubClosure: MoyaProvider.immediatelyStub)Clite
A
3

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.

Alliterate answered 12/11, 2018 at 8:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.