ios - How to partially mock external object -


i have class method test dependant object (keys object)

apirouter.m

+ (nsurl*)apiurlwithpath:(nsstring*)path {     mykeys *keys = [mykeys new];     nsstring *url = [nsstring stringwithformat:@"%@?api_key=%@", path, [keys apikey]];     return [nsurl urlwithstring:url]; } 

i trying partially mock keys object , return "my_api_key" value test method fails , returns real api key (e.g. as78d687as6d7das8da).

apirouterspec.m

describe(@"apirouter", ^{     it(@"should return url api", ^{         keys *keys = [keys new];         id keyspartialmock = ocmpartialmock(keys);         ocmstub([keyspartialmock apikey]).andreturn(@"my_api_key");         nsurl *url = [apirouter apiurlwithpath:@"http://www.api.com/v1/events"];         expect([url absolutestring]).to.equal([nsstring stringwithformat:@"http://www.api.com/v1/events?api_key=my_api_key"]);     }); }); 

maybe work you:

somewhere outside test method:

static nsstring *gmockapikey = @"my_api_key"; 

stub method this:

ocmstub([keyspartialmock apikey]).anddo(^(nsinvocation *invocation) {     [invocation setreturnvalue:&gmockapikey]; }); 

edit:

since apirouter using own instance of keys can try class mock:

id keysmock = ocmclassmock([keys class]); ocmstub(classmethod([keysmock apikey])).anddo(^(nsinvocation *invocation) {     [invocation setreturnvalue:&gmockapikey]; }); 

edit2:

so.. think proper way mock create mock instance of keys.

somewhere @ top of test file:

static keys *gmockedkeys = nil; static nsstring *gmockapikey = @"my_api_key"; 

setup:

- (void)setup {      [super setup];      gmockedkeys = [keys new];      id keyspartialmock = ocmpartialmock(gmockedkeys);     ocmstub([keyspartialmock apikey]).anddo(^(nsinvocation *invocation)     {         [invocation setreturnvalue:&gmockapikey];     }); } 

test:

- (void)testapiurlwithpath {      id keysmock = ocmclassmock([keys class]);     ocmstub([keysmock new]).andreturn(gmockedkeys);      nsurl *url = [apirouter apiurlwithpath:@"http://www.api.com/v1/events"];     nsstring *expectedurlstring = [url absolutestring];     xctassertequalobjects(expectedurlstring, @"http://www.api.com/v1/events?api_key=my_api_key", @"it should work now.."); } 

Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -