2013-05-04 49 views
2

我有以下方法:MagicalRecord MR_createInContext:返回nil

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]; 
    }); 

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

我有以下獼猴桃規範測試它問題是MR_createInContext方法返回一個零,我不知道可能是什麼原因,因爲在某些情況下她測試相同的代碼會生成一個有效的非零對象。

回答

0

正如你已經發現,當你設置一個receive期望,獼猴桃存根的對象方法,無論它是一個普通的對象,Class對象,或實際獼猴桃模擬/測試雙(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"]; 
}); 
0

那麼,像往常一樣,我放棄並進入堆棧溢出5秒後,我找到了答案。最初那麼我的

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

解釋是,原來的對象任何方式不影響它,這獼猴桃某種程度上知道這個對象應該接受這個選擇。原來,如果我測試,對象是否接收選擇器,這個對象被模擬或方法替換,因此正常的功能消失了。這就是我得到零的原因。

+0

你能重現這一結果與其他類(除MagicalRecord類別除外)?雖然我沒有試過用MagicalRecord專門重現這一點,但我[嘗試了一些人爲的代碼](https://gist.github.com/mmertsock/5519408)並且無法重現結果。 – 2013-05-05 02:12:15

+0

我會稍後檢查(這裏是凌晨3點),即使是調試器,也不會在我的測試用例中進入MR_createInContext的代碼。 – foFox 2013-05-05 02:43:31