OCMock a Class method to call back the passed block with custom Data

别来无恙 提交于 2019-12-12 18:37:48

问题


I do have a class that handles all my network communication like this:

typedef void (^ networkEndblock) (NSArray *, NSError *);

@interface NetworkAPI : NetworkBase

+ (void) doSomeNetworkAcion:(networkEndblock) endBlock;

@end

I use the above code like this (I do not want to get into irrelevant details here)

- (void) runMyProcess:(SomeEndBlock)proccesEnded{

  // Bussiness logic


  // Get Data from the web
  [NetworkAPI doSomeNetworkAcion:^(NSArray *resultArray, NSError *error){

   // Check for error. if we have error then do error handling
   // If no error, check for array.
   // If array is empty then go to code that handles empty array
   // else Process data                                 

   }];
}

In my test method I want to trigger runMyProcess to test, I do not want it to go and hit the network, I want to control that and set cases to make it return an error, empty array ...etc. I know how to use SenTest and it is MACROS but I do not how to fake my network API.

I looked into stubs and expect but I got confused if I can do what I want.

Thanks


回答1:


Class mock [NetworkAPI doSomeNetworkAction:] and use an andDo block.

// This is in the OCMock project but is really useful
#import "NSInvocation+OCMAdditions.h"

// Whatever you want for these values
NSArray *fakeResultArray;
NSError *fakeError;

id networkAPIMock = [OCMockObject mockForClass:NetworkAPI.class];
[[[networkAPIMock expect] andDo:^(NSInvocation *invocation) {
    networkEndBlock endBlock = [invocation getArgumentAtIndexAsObject:2];
    endBlock(fakeResultArray, fakeError);
}] doSomeNetworkAction:OCMOCK_ANY];

Also, I would capitalize NetworkEndBlock in my typedef as it will make your code easier to read for others.



来源:https://stackoverflow.com/questions/20692393/ocmock-a-class-method-to-call-back-the-passed-block-with-custom-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!