Strange ordering of Kiwi iOS context blocks

∥☆過路亽.° 提交于 2019-12-06 01:21:17

You are correct that [collection removeObject:object] is getting executed before the failing test. Think of Kiwi tests as operating in two passes:

  1. Setup: the code in your test file is executed from top to bottom to set up the test contexts and expectations
  2. Execution: each unit test is run, basically one per it/specify statement, with the correct setup/teardown code repeated for each test

Note that most of the code in a Kiwi test file is specified as a series of blocks sent to the Kiwi functions. Any code that doesn't follow the Kiwi block patterns, such as your code that initializes/modifies the collection variable, might thus execute at an unexpected time. In this case, all of the collection modification code is being executed during the first pass when setting up your tests, and then your tests are run.

Solution

Declare collection with a __block modifier, and use beforeEach to instantiate and modify the collection object:

describe(@"Collection starting with no objects", ^{
    __block MyCollection *collection;
    beforeEach(^{
        collection = [MyCollection new];
    });

    context(@"then adding 1 object", ^{
        beforeEach(^{
            MyObject *object = [MyObject new];
            [collection addObject:object];
        });
        it(@"has 1 object", ^{
            ...
        });

        context(@"then removing 1 object", ^{
            beforeEach(^{
                [collection removeObject:object];
            });
            it(@"has 0 objects", ^{
                ...

The beforeEach blocks tell Kiwi to specifically run the given code once per unit test, and with nested contexts, the blocks will be executed in sequence as needed. So Kiwi will do something like this:

// run beforeEach "Collection starting with no objects"
collection = [MyCollection new]
// run beforeEach "then adding 1 object"
MyObject *object = [MyObject new]
[collection addObject:object]
// execute test "has 1 object"
[collection shouldNotBeNil]
[collection.objects shouldNotBeNil]
[[theValue(collection.objects.count) should] equal:theValue(1)]

// run beforeEach "Collection starting with no objects"
collection = [MyCollection new]
// run beforeEach "then adding 1 object"
MyObject *object = [MyObject new]
[collection addObject:object]
// run beforeEach "then removing 1 object"
[collection removeObject:object]
// execute test "has 0 objects"
[[theValue(collection.objects.count) should] equal:theValue(0)]

The __block modifier will ensure that the collection object reference can be properly retained and modified through all of these block functions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!