如何使用OCMock根据不同的参数返回不同的结果

时间:2016-04-19 17:57:05

标签: ocmock

我试图在为同一方法传递不同的参数时模拟不同的方法返回。

self.myMock = [OCMockObject mockForClass:[MyClass class]];
[[[self.myMock expect] andReturnValue:5] myStaticMethod:3];
[[[self.myMock expect] andReturnValue:10] myStaticMethod:6];

但它只需要第一个,当参数为3然后返回5,当参数为6时,它返回nil而不是10.有没有人知道是否有一种方法来测试它?

真实代码:

-(NSMutableArray*)convertChildStringToChildDic:(NSString*)strchildren
{
    NSArray *kididarray = [strchildren componentsSeparatedByString:@","];
    //处理小孩信息
    /*children =             (
     {
     avatarSmall = "<null>";
     currentStatus = 0;
     displayName = stu1;
     "id_str" = "70938032-3811-e411-946a-005056c00008";
     title = Child;
     }
     )*/
    NSMutableArray *rstchildarray = [NSMutableArray arrayWithCapacity:1];
    for (NSString *enrollment_id in kididarray) {
        if (enrollment_id.length <= 0) {
            continue;
        }
        **NSMutableDictionary *mdic = [[RoomInfoManager sharedManager] getKidDictionaryByID:enrollment_id];**

        [mdic setValue:enrollment_id forKey:@"id_str"];
        if (mdic != nil) {
            [rstchildarray addObject:mdic];
        }
    }
    return rstchildarray;
}

测试:

-(void) testconvertChildStringToChildDic_InvalidAgruments {
    NSMutableDictionary *childdic = [[NSMutableDictionary alloc] init];
    childdic[@"id"] = @"josh";

    NSMutableDictionary *childdic1 = [[NSMutableDictionary alloc] init];
    childdic1[@"id"] = @"joy";


    id mockRIM = OCMClassMock([RoomInfoManager class]);
    **OCMStub([mockRIM getKidDictionaryByID:@"josh"]).andReturn(childdic);
    **OCMStub([mockRIM getKidDictionaryByID:@"joy"]).andReturn(childdic1);****


    RoomInfoManager *roomInfoMgr = [RoomInfoManager alloc];
    id mockPartialRIM = OCMPartialMock(roomInfoMgr);

    OCMExpect([mockPartialRIM sharedManager]).andReturn(mockRIM); // use expect

    NSString *childStr = @"josh,joy";
    NSMutableArray *childarray = [[ReportOperator alloc] convertChildStringToChildDic:childStr];

    NSDictionary *childrenArraydic = @{@"id" : @"josh", @"id_str": @"josh"};
    NSMutableArray *resultArray = [NSMutableArray arrayWithObjects:childrenArraydic, nil];

    [mockPartialRIM verify]; // verify expect,验证该对像是否被调用。

    XCTAssertEqualObjects(childarray, resultArray);
}

第二次电话

OCMStub([mockRIM getKidDictionaryByID:@"joy"]).andReturn(childdic1);

似乎没有生效,而是返回nil。

0 个答案:

没有答案