Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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