OCMock and block testing, executing

前端 未结 3 2106
傲寒
傲寒 2021-02-05 22:44

Here\'s the method under test:

- (void)loginWithUser:(NSString *)userName andPass:(NSString *)pass {

    NSDictionary *userPassD = @{@\"user\":userName,
                


        
3条回答
  •  情话喂你
    2021-02-05 23:33

    If I follow you right, this may do what you want:

    @interface ExampleLC : NSObject
    - (void)loginWithUserPass:userPassD withSuccess:(void (^)(NSString *authToken))successBlock failure:(void (^)(NSString *errorMessage))failureBlock;
    @end
    @implementation ExampleLC
    - (void)loginWithUserPass:userPassD withSuccess:(void (^)(NSString *authToken))successBlock failure:(void (^)(NSString *errorMessage))failureBlock
    {
    }
    @end
    @interface Example : NSObject {
        @public
        ExampleLC *_loginCntrl;
    }
    - (void)saveToken:(NSString *)authToken;
    - (void)loginWithUser:(NSString *)userName andPass:(NSString *)pass;
    @end
    @implementation Example
    - (void)saveToken:(NSString *)authToken
    {
    }
    - (void)loginWithUser:(NSString *)userName andPass:(NSString *)pass {
    
        NSDictionary *userPassD = @{@"user":userName,
                                    @"pass":pass};
        [_loginCntrl loginWithUserPass:userPassD withSuccess:^(NSString *authToken){
            // save authToken to credential store
            [self saveToken:authToken];
        } failure:^(NSString *errorMessage) {
            // alert user pass was wrong
        }];
    }
    @end
    
    
    @interface loginTest : SenTestCase
    
    @end
    
    @implementation loginTest
    
    - (void)testExample
    {
        Example *exampleOrig = [[Example alloc] init];
        id loginCntrl = [OCMockObject mockForClass:[ExampleLC class]];
        [[[loginCntrl expect] andDo:^(NSInvocation *invocation) {
            void (^successBlock)(NSString *authToken) = [invocation getArgumentAtIndexAsObject:3];
            successBlock(@"Dummy");
        }] loginWithUserPass:OCMOCK_ANY withSuccess:OCMOCK_ANY failure:OCMOCK_ANY];
        exampleOrig->_loginCntrl = loginCntrl;
        id example = [OCMockObject partialMockForObject:exampleOrig];
        [[example expect] saveToken:@"Dummy"];
        [example loginWithUser:@"ABC" andPass:@"DEF"];
        [loginCntrl verify];
        [example verify];
    }
    @end
    

    This code allows forces the real success block to be invoked with the argument you specify, which you can then verify.

提交回复
热议问题