Back

How to Mock AFNetworking Requests

Occasionally, you may need to mock AFNetworking responses to test your response handling code. You can mock these in XCTestCases by setting up a category to return a response file when a network request is made.

1. Import the BOURLProtocol header and implementation files into your XCTest target.
2. Register a special protocol in your XCTestCase.
3. Stub a path in your XCTestCase and pass it the response that you want your request to return.
4. Add a small artificial delay to wait for the request to finish (AFNetworking requests are typically asynchronous).
5. Unregister your special protocol.

Example TestCase

  1. #import "BOURLProtocol.h"
  2. @implementation TestCase
  3. - (void)testSomething
  4. {
  5. [BOURLProtocol registerSpecialProtocol];
  6. [BOURLProtocol stubPath:@"URL_Path" load:[[NSBundle bundleForClass:[self class]] URLForResource:@"ResponseSuccess"
  7. withExtension:@"json"]];
  8. // Do something that requires a network request
  9. // Delay since AFNetworking makes asynchronous requests
  10. NSDate *until = [NSDate dateWithTimeIntervalSinceNow:0.5];
  11. while ([until timeIntervalSinceNow] > 0)
  12. {
  13. [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
  14. beforeDate:until];
  15. }
  16. // Verify expected behavior
  17. [BOURLProtocol unregisterSpecialProtocol];
  18. }
  19. @end

 

SEE OUR JOB OPENINGS

Metova
Metova