簡體   English   中英

OCMock故障在NSMutableAttributedString上模擬'initWithAttributedString'

[英]OCMock failure mocking 'initWithAttributedString' on NSMutableAttributedString

我試圖了解什么是可模仿的,什么不是。

在使用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調用,而我不應該使用。

我非常感謝您對此進行一些澄清,並暗示了上述原因為何不起作用。

謝謝喬

學到了一些關於Objective-C的知識,試圖弄清楚這一點。

您的基本問題是,通過分配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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM