NSMutableAttributedString

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调用,而我不应该使用。

我非常感谢您对此进行一些澄清,并暗示了上述原因为何不起作用。

谢谢,

最佳答案

learned something about 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

关于ios - OCMock故障在NSMutableAttributedString上模拟'initWithAttributedString',我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15360082/

10-14 05:37