Hi,
Please find below for "Unit Testing of BLOCK's using OCMock in Objective C".
Example Class:
MyClass.h
//Here, we have a class with a delegate property and methods.
@protocol MyClassDelegate <NSObject>
-(void)DidEndWithErrorMessage:(NSString *)message;
@end
@interface MyClass : NSObject
@property (assign) id <MyClassDelegate> delegate;
//This is the method, which will return the block
- (void (^)(NSError *, id))handleRequestResponse;
- (void)getRequestDetails;
@end
MyClass.m
@implementation MyClass
@synthesize delegate = _delegate;
//Implement the method for unit testing
- (void (^)(NSError *, id))handleRequestResponse
{
void (^completionBlock)(NSError *, id) = [^(NSError *error, id response) {
if(error)
{
[[self delegate] DidEndWithErrorMessage:[error localizedDescription]];
}
} copy];
return [completionBlock autorelease];
}
- (void)getRequestDetails
{
[RequestManager requestForDetailsUsingBlock:[self handleRequestResponse]];
}
@end
And Unit Testing Classes:
MyClassTests.h
#import <SenTestingKit/SenTestingKit.h>
@interface MyClassTests : SenTestCase
@end
MyClassTests.m
#import <OCMock/OCMock.h>
#import "MyClass.h"
@interface MyClassTests ()
{
MyClass *_instance;
}
@end
@implementation MyClassTests
-(void)setUp
{
[super setUp];
_instance = [[MyClass alloc] init];
}
-(void)tearDown
{
[_instance release];
[super tearDown];
}
-(void)testCreditFacilityAccountDetailsErrorReponse
{
//set expected error string into separate local variable
NSString *errorMessage = @"Testing Blocks using OCMock";
//An error object to pass it as an argument to block
NSError *error = [[NSError alloc] initWithDomain:nil code:0 userInfo:[NSDictionary dictionaryWithObject:errorMessage forKey:NSLocalizedDescriptionKey]];
//mock the response object, which is also one of the argument to block
id mockResponse = [OCMockObject mockForClass:[NSDictionary class]];
//You can stub/expect methods here
//mock the delegate so that we can verify the error message
id mockDelegate = [OCMockObject mockForProtocol:@protocol(MyClassDelegate)];
[[mockDelegate expect] DidEndWithErrorMessage:[OCMArg checkWithBlock:^BOOL(id message)
{
STAssertEqualObjects(errorMessage, message, @"It should match the expected error message");
}]];
[_instance setDelegate:mockDelegate];
//Set the mocked delegate
//Get the response Block
void (^responseBlock)(NSError *, id) = [_instance handleRequestResponse];
//Invoking a block
responseBlock(error,mockResponse);
//Verify the mocke delegate instance
[mockDelegate verify];
[error release];
}
@end
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.