如何用 Kiwi 2,Objective-C 存根只读 属性

How to stub readonly property with Kiwi 2, Objective-C

寻找有关使用 Kiwi 访问只读 属性 的小帮助。 简而言之,我想测试 _myReadOnlyDict 是否被初始化。 问题是 myReadOnlyDict 仍然总是空的(没有内容),尽管在 beforeEach 块中它被模拟并添加了一个值。

    // All these return 0
    ad.myReadOnlyDict.count;
    [[ad myReadOnlyDict] allKeys].count;
    [ad myReadOnlyDict].count;

我在这里缺少什么?

感谢任何帮助!

请看下面的代码:

在AppDelegate.h我有一处房产。

@property (nonatomic, readonly) NSDictionary * myReadOnlyDict;

在 AppDelegate.m 我有一个方法,它是从 AppDelegate 的 didFinishLaunchingWithOptions 方法调用的。

- (void)initConfig
{
    _myReadOnlyDict = [NSJSONSerialization JSONObjectWithData:[self jsonData] options:nil error:nil];
}

我设置了 Kiwi 测试

describe(@"App Delegate", ^{

    __block AppDelegate *ad;

    beforeEach(^{
        ad = [[AppDelegate alloc] init];

        NSMutableDictionary * mockedDict = [NSJSONSerialization nullMock];

        mockedDict[@"my_data"] = @"my_value";

        [ad stub:@selector(myReadOnlyDict) andReturn:mockedDict];
    });

    afterEach(^{
        ad = nil;
    });

    context(@"when smth happens", ^{
        it(@"should do smth else", ^{
            [[ad should] receive:@selector(initConfig)];

            // These three lines fail
            [[theValue([ad myReadOnlyDict].count) shouldNot] equal:theValue(0)];
            [[theValue(ad.myReadOnlyDict.count) shouldNot] equal:theValue(0)];
            [[theValue([[ad myReadOnlyDict] allKeys].count) shouldNot] equal:theValue(0)];

            [ad initConfig];
        });
    });
});

你的问题是由于 [NSJSONSerialization nullMock]returns 是一个 null mock,它是一个对任何调用的方法都不做任何事情的对象,returns nil/0 到任何必须 return 东西的方法。

这应该有效:

NSMutableDictionary * mockedDict = [@{@"my_data": @"my_value"} mutableCopy];
[ad stub:@selector(myReadOnlyDict) andReturn:mockedDict];