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
- #
import "BOURLProtocol.h"
@implementation TestCase
- (
void
)testSomething
{
[BOURLProtocol registerSpecialProtocol];
[BOURLProtocol stubPath:@
"URL_Path"
load:[[NSBundle bundleForClass:[self
class
]] URLForResource:@
"ResponseSuccess"
withExtension:@
"json"
]];
// Do something that requires a network request
// Delay since AFNetworking makes asynchronous requests
NSDate *until = [NSDate dateWithTimeIntervalSinceNow:0.5];
while
([until timeIntervalSinceNow] > 0)
{
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
beforeDate:until];
}
// Verify expected behavior
[BOURLProtocol unregisterSpecialProtocol];
}
@end