1

我试图了解什么是可模拟的,什么不是。

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

我非常感谢对此进行澄清,并提示为什么上述方法不起作用。

谢谢,乔

4

1 回答 1

2

学到了一些关于 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
于 2013-04-19T18:32:35.717 回答