gpt4 book ai didi

ios - MagicalRecord MR_createInContext : returns nil

转载 作者:行者123 更新时间:2023-12-01 16:50:33 25 4
gpt4 key购买 nike

我有以下方法:

+(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;
}

我正在使用以下 Kiwi 规范对其进行测试:
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 对象。

最佳答案

正如您所发现的,当您设置 receive期望,Kiwi 在对象上 stub 该方法,无论它是否是常规对象,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"];
});

关于ios - MagicalRecord MR_createInContext : returns nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16379820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com