FIRURLSessionOCMockStub.m 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright 2020 Google LLC
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "SharedTestUtilities/URLSession/FIRURLSessionOCMockStub.h"
  17. #import <OCMock/OCMock.h>
  18. @implementation FIRURLSessionOCMockStub
  19. + (id)stubURLSessionDataTaskWithResponse:(NSHTTPURLResponse *)response
  20. body:(NSData *)body
  21. error:(NSError *)error
  22. URLSessionMock:(id)URLSessionMock
  23. requestValidationBlock:(FIRRequestValidationBlock)requestValidationBlock {
  24. id mockDataTask = OCMStrictClassMock([NSURLSessionDataTask class]);
  25. // Validate request content.
  26. FIRRequestValidationBlock nonOptionalRequestValidationBlock =
  27. requestValidationBlock ?: ^BOOL(id request) {
  28. return YES;
  29. };
  30. id URLRequestValidationArg = [OCMArg checkWithBlock:nonOptionalRequestValidationBlock];
  31. // Save task completion to be called on the `[NSURLSessionDataTask resume]`
  32. __block void (^taskCompletion)(NSData *, NSURLResponse *, NSError *);
  33. id completionArg = [OCMArg checkWithBlock:^BOOL(id obj) {
  34. taskCompletion = obj;
  35. return YES;
  36. }];
  37. // Expect `dataTaskWithRequest` to be called.
  38. OCMExpect([URLSessionMock dataTaskWithRequest:URLRequestValidationArg
  39. completionHandler:completionArg])
  40. .andReturn(mockDataTask);
  41. // Expect the task to be resumed and call the task completion.
  42. OCMExpect([(NSURLSessionDataTask *)mockDataTask resume]).andDo(^(NSInvocation *invocation) {
  43. taskCompletion(body, response, error);
  44. });
  45. return mockDataTask;
  46. }
  47. + (NSHTTPURLResponse *)HTTPResponseWithCode:(NSInteger)statusCode {
  48. return [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:@"http://localhost"]
  49. statusCode:statusCode
  50. HTTPVersion:@"HTTP/1.1"
  51. headerFields:nil];
  52. }
  53. @end