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调用我可以期望工作,哪些我不应该。

我将非常感谢你对这一点的澄清,并提示为什么以上不起作用。

谢谢,乔

为了解决这个问题,我学到了一些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

相关内容

  • 没有找到相关文章

最新更新