简体   繁体   English

如何使用Kiwi 2,Objective-C存根readonly属性

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

looking for little help on accessing readonly property with Kiwi. 在使用Kiwi访问只读属性方面寻求帮助。 In short, I want to test if _myReadOnlyDict gets initialized or not. 简而言之,我想测试_myReadOnlyDict是否已初始化。 Problem is that myReadOnlyDict is still always empty(has no contents), despite that in beforeEach block it is mocked and a value added to it. 问题是,尽管在beforeEach块中对beforeEach并为其添加了值,但myReadOnlyDict仍然始终为空(无内容)。

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

What I am missing here? 我在这里想念的是什么?

Any help is appreciated! 任何帮助表示赞赏!

Please see the code below: 请参见下面的代码:

In AppDelegate.h I have a porperty. 在AppDelegate.h中,我有一个功能。

@property (nonatomic, readonly) NSDictionary * myReadOnlyDict;

In AppDelegate.m I have a method, which is called from AppDelegate's didFinishLaunchingWithOptions method. 在AppDelegate.m中,我有一个方法,该方法是从AppDelegate的didFinishLaunchingWithOptions方法调用的。

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

I have a Kiwi test set up 我设置了猕猴桃测试

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];
        });
    });
});

Your problem is caused by the fact that [NSJSONSerialization nullMock] returns a null mock, which is an object that does nothing for any called method, and returns nil /0 to any method that must return something. 您的问题是由以下事实引起的: [NSJSONSerialization nullMock]返回一个空模拟,这是一个对任何调用的方法[NSJSONSerialization nullMock]执行任何操作的对象,并且向必须返回内容的任何方法返回nil / 0。

This should work: 这应该工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM