1

I would like to test a method which makes a GET request.

Here's a contrived example:

- (void)GET:(NSString *)URLString;

Rather than worry about the implementation details of this method (e.g. mocking, setting expectations, and then verifying a dependency), I'd prefer to just be able to test if the GET request was made.

I believe I can do this with NSURLProtocol but my attempts so far have been unsuccessful.

For example, using OCMock:

id mockURLProtocol = (NSURLProtocol *)[OCMockObject mockForClass:[NSURLProtocol class]];
[NSURLProtocol registerClass:mockURLProtocol];

[[mockURLProtocol expect] canInitWithRequest:[OCMArg any]];

[MYClass GET:@"test"];

[mockURLProtocol verify];
[mockURLProtocol stopMocking];
[NSURLProtocol unregisterClass:mockURLProtocol];

The above test fails since canInitWithRequest is never called.

How can I set expectations on NSURLProtocol to verify that the request is being made?

Paul Young
  • 1,489
  • 1
  • 15
  • 34
  • To clarify, I realize that the above is only a starting point and that I'd need to do more work to verify that the request I expected is actually made. – Paul Young Jan 30 '14 at 16:07
  • What is the code for your class's GET method? – Ben Flynn Jan 30 '14 at 17:26
  • It currently uses AFNetworking, but the point is not to really care what's going on inside the method. – Paul Young Jan 30 '14 at 19:01
  • Here you're verifying that your GET method will call "canInitWithRequest" -- it's not clear to me that it would -- that method could do anything. If you want to know if a GET request was made, why not partial mock your own class instance and expect "GET"? – Ben Flynn Jan 30 '14 at 19:49
  • In this case the method under test is `GET`. That's method I'm going to call. If a GET request is made and my NSURLProtocol mock is registered, `canInitWithRequest` should be called. – Paul Young Jan 30 '14 at 20:14
  • check out http://www.infinite-loop.dk/blog/2011/09/using-nsurlprotocol-for-injecting-test-data/ , it has a working example for using NSURLProtocol for unit testing – ekeren Mar 02 '14 at 12:47

1 Answers1

0

Mocking NSURLProtocol doesn't make sense to me. NSURLProtocol is used in testing to create canned responses to certain requests, there is no need of mocking it (you don't want to test how the system interacts with it). This project makes use of NSURLProtocol, it may be useful for you in case you want to use this approach instead of a pure unit test where you test your NSURLConnectionDelegate implementation directly.

e1985
  • 6,239
  • 1
  • 24
  • 39