I have written a lot of error handling code for really improbable response status codes from the server. Now I want to test it. Do I send a message to the server guy and ask him to break the server or can I make my testing provider return status codes other than 200?
This sounds like a great use case for sampleResponseClosure! I'm going to pull an example from the Ello app (https://github.com/ello/ello-ios - ElloProvider_Specs.swift)
You just need to configure a Provider instance to return errors - this is a little different from stubbing:
static func errorEndpointsClosure(target: ElloAPI) -> Endpoint<ElloAPI> {
let sampleResponseClosure = { () -> EndpointSampleResponse in
return .NetworkResponse(500, NSData()) // you can & should have this configurable - globals, or properties on your Target
}
// all the request properties should be the same as your default provider
let method = target.method
let parameters = target.parameters
let endpoint = Endpoint<ElloAPI>(URL: url(target),
sampleResponseClosure: sampleResponseClosure, // <- here goes!
method: method, parameters: parameters)
return endpoint.endpointByAddingHTTPHeaderFields(target.headers())
}
Ok so that's the first half - the second half is to configure a Provider to _use_ this "endpoint generator"
public static func ErrorStubbingProvider() -> MoyaProvider<ElloAPI> {
return MoyaProvider<ElloAPI>(endpointClosure: errorEndpointsClosure, stubClosure: MoyaProvider.ImmediatelyStub)
}
In the Ello specs, we use this by assigning globals in our setup code, and assigning this provider as the "default provider"
ElloProvider.sharedProvider = ElloProvider.ErrorStubbingProvider()
ElloProvider_Specs.errorStatusCode = .Status502 // this is an enum we define in ErrorStatusCode.swift
Sorry about the late response to an incredibly quick response! This does indeed look like it's the way to do it. Just the answer I was looking for, many thanks!
馃憤 Close it up!
Most helpful comment
This sounds like a great use case for
sampleResponseClosure! I'm going to pull an example from the Ello app (https://github.com/ello/ello-ios -ElloProvider_Specs.swift)You just need to configure a Provider instance to return errors - this is a little different from stubbing: