I have a class Network that contain next method:
- (void)fetchRecords {
Network * __weak weakSelf = self;
[self.sessionManager POST:@"" parameters:@{@"parameter":"param1"}
success:^(NSURLSessionDataTask *task, id responseObject) {
[weakSelf setRecordsWithLists:responseObject];
}
failure:nil];
}
Property sessionManager
is AFHTTPSessionManager
class.
I want to test my network communication. I want to check that if success block executed then invoked setRecordsWithLists:
method.
I use OCMock, I googled and write next test code:
- (void)tesNetworkSuccessExecuteSetRecords {
id partiallyMockedSessionManager = [OCMockObject partialMockForObject:self.network.sessionManager];
[[partiallyMockedSessionManager expect] POST:OCMOCK_ANY parameters:OCMOCK_ANY success:OCMOCK_ANY failure:OCMOCK_ANY];
[[[partiallyMockedSessionManager expect] andDo:^(NSInvocation *invocation) {
void (^successBlock)(NSURLSessionDataTask *task, id responseObject);
[invocation getArgument:&successBlock atIndex:4];
successBlock(nil, @[@"first", @"second"]);
}] POST:OCMOCK_ANY parameters:OCMOCK_ANY success:OCMOCK_ANY failure:OCMOCK_ANY];
self.network.sessionManager = partiallyMockedAuthorizationSessionManager;
[self.network fetchRecords];
}
Please, tell how to return my own response for success block, if do it wrong. And how to verify that setRecordsWithLists:
called from success block.
Well, you are actually setting the expectation twice, which would mean you are expecting the method to be called twice too. If that is not what you intend, you should delete the first expectation.
On the other hand, since you need to check if your method is called, you probably want to create a partial mock for your self.network
object. With the partial mock (or spy), you can set the expectation for your method, with any argument you prefer, and verify it to complete the test.
Your code finally should look like this:
- (void)tesNetworkSuccessExecuteSetRecords {
id partiallyMockedSessionManager = [OCMockObject partialMockForObject:self.network.sessionManager];
[[[partiallyMockedSessionManager expect] andDo:^(NSInvocation *invocation) {
void (^successBlock)(NSURLSessionDataTask *task, id responseObject);
[invocation getArgument:&successBlock atIndex:4];
successBlock(nil, @[@"first", @"second"]);
}] POST:OCMOCK_ANY parameters:OCMOCK_ANY success:OCMOCK_ANY failure:OCMOCK_ANY];
id spyNetwork = OCMPartialMock(self.network);
[[spy expect] setRecordsWithLists:OCMOCK_ANY];
self.network.sessionManager = partiallyMockedAuthorizationSessionManager;
[self.network fetchRecords];
[spyNetwork verify];
}
Again, you may add the argument of your preference in the expectation. Beware of the name of the method, it should begin with 'test', otherwise it may not be run or recognized as a test by XCode.