2

我有以下方法:

+(Group*)groupWithID:(NSString *)idNumber
           inContext:(NSManagedObjectContext *)context
{
    Group *group = nil;
    if(idNumber && context)
    {
        NSArray *result = [Group MR_findByAttribute:@"idNumber" withValue:idNumber inContext:context];
        if(!result || result.count > 1)
        {
            // TODO (Robert): Handle error for more than one group objects or error nil results
        }
        else if(result.count == 0)
        {
            group = [Group MR_createInContext:context];
            group.idNumber = idNumber;
            NSAssert(group != nil, @"Group should not be nil!");
        }
        else
        {
            group = [result lastObject];
        }
    }

    return group;
}

我正在使用以下猕猴桃规格对其进行测试:

it(@"should create new object with new id", ^{
    [[[Group class] should] receive:@selector(MR_createInContext:)];
    Group *group = [Group groupWithID:@"12345"
                            inContext:[NSManagedObjectContext MR_contextForCurrentThread]];
    [[group should] beNonNil];
    [[[group idNumber] should] equal:@"12345"];
});

使用以下设置:

beforeEach(^{
        [MagicalRecord setupCoreDataStackWithInMemoryStore];
        [MagicalRecord setDefaultModelNamed:@"Model.mom"];
    });

    afterEach(^{
        [MagicalRecord cleanUp];
    });

问题是方法 MR_createInContext 返回一个 nil,我不知道可能是什么原因,因为在其他一些测试中,相同的代码会产生一个有效的非 nil 对象。

4

2 回答 2

0

好吧,像往常一样,在我放弃并进入堆栈溢出后 5 秒,我找到了答案。好吧,最初我的解释是

[[[object should] receive:@selector(selector_name:)];

是原始对象不会以任何方式受到影响,并且猕猴桃不知何故知道该对象应该接收此选择器。事实证明,如果我测试,对象是否接收选择器,这个对象会被替换为模拟或方法被混合,因此正常功能消失了。这就是我得到零的原因。

于 2013-05-04T23:23:29.210 回答
0

正如您所发现的,当您设置receive期望时,Kiwi 会在对象上存根该方法,无论它是常规对象、Class对象还是实际的 Kiwi 模拟/测试替身(https://github.com/allending/ Kiwi/wiki/Expectations#expectations-interactions-and-messages)。

如果您要测试的是您的助手行为正确,那么您实际上+groupWithID:inContext:并不想要MR_createInContext:. “应该收到”的期望旨在测试您是否发送了正确的消息,但要避免执行实际代码。

也许是这样的:

it(@"creates a new group if one does not exist with the specified id", ^{
    // stub MR_findByAttribute to return no results
    [Group stub:@selector(MR_findByAttribute:withValue:inContext:) andReturn:@[]];

    // stub MR_createInContext to use our test group so that we can set
    // expectations on it
    id context = [NSManagedObject MR_defaultContext];
    id group = [Group MR_createInContext:context];
    [[Group should] receive:@selector(MR_createInContext:) andReturn:group withArguments:context];

    // call the method we want to test
    [Group groupWithID:@"1234" inContext:context];

    // test that the id was set correctly
    [[group.idNumber should] equal:@"1234"];
});
于 2013-05-05T07:37:30.733 回答