Skip to content

Instantly share code, notes, and snippets.

@vtourraine
Created March 8, 2018 16:09
Show Gist options
  • Save vtourraine/06b4f6e762e58b5ac941ca6cd19235e3 to your computer and use it in GitHub Desktop.
Save vtourraine/06b4f6e762e58b5ac941ca6cd19235e3 to your computer and use it in GitHub Desktop.
Test block as parameter with OCMock
//
// NetworkManager.h
//
@import Foundation;
@interface NetworkManager : NSObject
- (void)fetchDataCompletion:(void(^)(NSString *))completion;
- (void)GET:(NSString *)path completion:(void(^)(NSData *))completion;
@end
//
// NetworkManager.m
//
#import "NetworkManager.h"
@implementation NetworkManager
- (void)fetchDataCompletion:(void(^)(NSString *))completion {
[self GET:@"/blabla" completion:^(NSData *data) {
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
completion(string);
}];
}
- (void)GET:(NSString *)path completion:(void(^)(NSData *))completion {
}
@end
//
// TestMockTests.m
//
@import XCTest;
#import "NetworkManager.h"
#import <OCMock.h>
@interface TestMockTests : XCTestCase
@end
@implementation TestMockTests
- (void)testExample {
NetworkManager *manager = [[NetworkManager alloc] init];
id mockManager = OCMPartialMock(manager);
NSData *stubData = [@"success" dataUsingEncoding:NSUTF8StringEncoding];
OCMStub([mockManager GET:@"/blabla" completion:([OCMArg invokeBlockWithArgs:stubData, nil])]);
XCTestExpectation *expectation = [self expectationWithDescription:@"should be a success"];
[mockManager fetchDataCompletion:^(NSString *response) {
XCTAssertEqualObjects(response, @"success");
[expectation fulfill];
}];
[self waitForExpectations:@[expectation] timeout:1];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment