2013-03-12 43 views
1

我想了解什麼是可嘲諷的,什麼是嘲笑。OCMock故障模仿NSMutableAttributedString上的'initWithAttributedString'

在一個NSMutableAttributedString的實驗中,我似乎無法模擬initWithAttributedString

- (void)test_mutableString_shouldWorkAsAMutableString { 
    NSMutableAttributedString *_mutable = [OCMockObject mockForClass:NSMutableAttributedString.class]; 
    NSAttributedString *_string = [OCMockObject mockForClass:NSAttributedString.class]; 
    [[[(id)_mutable expect] andReturnValue:nil] initWithAttributedString:_string]; 
    [_mutable initWithAttributedString:_string]; 
} 

此代碼不會運行;由於某種原因,對可變屏幕代理不承認initWithAttributedString選擇:

2013-03-12 11:25:30.725 UnitTests[11316:c07] TestItClass/test_4_mutableString_shouldWorkAsAMutableString ✘ 0.00s 

    Name: NSInvalidArgumentException 
    File: Unknown 
    Line: Unknown 
    Reason: *** -[NSProxy doesNotRecognizeSelector:initWithAttributedString:] called! 

    0 CoreFoundation      0x01c0602e __exceptionPreprocess + 206 
    1 libobjc.A.dylib      0x01948e7e objc_exception_throw + 44 
    2 CoreFoundation      0x01c05deb +[NSException raise:format:] + 139 
    3 Foundation       0x00862bcd -[NSProxy doesNotRecognizeSelector:] + 75 
    4 CoreFoundation      0x01bf5bbc ___forwarding___ + 588 
    5 CoreFoundation      0x01bf594e _CF_forwarding_prep_0 + 14 
    6 UnitTests       0x00349e0b -[TestItClass test_4_mutableString_shouldWorkAsAMutableString] + 283 

我想明白,我怎麼能可靠地使用OCMock,但這種混淆我的,我不知道哪個OCMock要求我可以期望工作,而我不應該這樣做。

我非常感謝這方面的一些澄清,以及爲什麼上述不起作用的提示。

謝謝, 喬

+0

爲什麼您需要模擬NSAttributedString? – 2013-04-19 20:01:57

+0

大衛,我有一些業務邏輯,以特定的方式構建NSAttributedString。爲了測試該邏輯,我需要模擬歸因字符串來測試交互。 – 2013-04-25 22:03:36

回答

2

learned something about Objective-C試圖找出這一個。

你的基本問題是,由alloc'ing NSMutableAttributedString創建的對象的類不是NSMutableAttributedString(始終保持免費的橋接類)。要使您的代碼正常工作,請嘗試以下操作:

NSMutableAttributedString *realMutable = [[NSMutableAttributedString alloc] init]; 
id mutable = [OCMockObject niceMockForClass:[realMutable class]]; 
id string = [OCMockObject niceMockForClass:[NSAttributedString class]]; 

[[[mutable expect] andReturn:@"YO" ] initWithAttributedString:string]; 
NSLog(@"MOCK: %@", [mutable initWithAttributedString:string]); 

[mutable verify]; 

// Outputs 'MOCK: YO' and passes 
+0

啊,我明白了。這是一種很好的方式來隱藏這種干擾,並仍然使測試代碼可維護。謝謝! – 2013-04-25 22:05:15