Reputation: 5104
What are the best practices for mocking out server responses (JSON) for an iOS app?
Situation is that one developer (not me) is making the backend and I want to create a "mock server" so I can start user testing with pseudo data and also for unit tests.
Are there any frameworks that 'intercept' nsurlconnection so I can inject my own json response if I dont' actually want to reach out to a server? Currently I'm switching on a flag inside of all my server request methods and its kind of ugly.
Upvotes: 2
Views: 2020
Reputation: 1539
Check Nocillap, one of the coolest mocking libraries for iOS/OSX development:
stubRequest(@"POST", @"https://api.example.com/dogs.json").
andReturn(201).
withHeaders(@{@"Content-Type": @"application/json"});
Works with AFNetworking which is a huge these days.
Upvotes: 2
Reputation: 18477
For server communication I abstract away NSURLConnection
with my own 'service request' class. This decouples my code from server-specific logic and error handling, but also is nice because mocking out the response data proves to be extremely easy. You can set to use the mock data through configuration, or as @wkhatch mentions, conditionally compile it.
Upvotes: 2
Reputation: 2741
You could define a protocol, have your dependent classes use the protocol as the type, and then create a few different classes that implement it; one for live, one for testing, etc Then, inside your dependent controller or wherever you need to switch, just use a target or config pre proc to switch out which one gets used. When using a protocol in this way, you want to define it like:
id<ProtocolName> myServerURLConnectionThing;
This certainly isn't the only way to do what you want, but basically, it's all going to come down to abstracting out the interface you need one way or the other. HTH
Upvotes: 0