奇怪的猕猴桃 iOS 上下文块排序

标签: ios Objective-C
发布时间: 2017/3/21 22:58:20
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我有一个猕猴桃的 spec 文件,看起来像这样︰

#import "Kiwi.h"
#import "MyCollection.h"

SPEC_BEGIN(CollectionSpec)

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

    context(@"then adding 1 object", ^{
        MyObject *object = [MyObject new];
        [collection addObject:object];
        it(@"has 1 object", ^{
            [collection shouldNotBeNil];
            [collection.objects shouldNotBeNil];
            [[theValue(collection.objects.count) should] equal:theValue(1)]; //failing test
        });

        context(@"then removing 1 object", ^{
            [collection removeObject:object];
            it(@"has 0 objects", ^{
                [[theValue(collection.objects.count) should] equal:theValue(0)]; //passing test
            });
        });
    });
});

SPEC_END

在一次失败就在这行代码运行 spec 结果[[theValue(collection.objects.count) should] equal:theValue(1)];

这里是奇怪的部分-,如果删除了整个 context(@"then removing 1 object", ^{...}) 块从上述测试通过这个规范。

这使我相信 [collection removeObject:object] 线得到执行之前失败的测试。我有一种感觉,我可能误解块中执行的顺序。

任何建议,将不胜感激 !

解决方法 1:

你是正确的 [collection removeObject:object] 在失败的测试之前得到执行。认为的猕猴桃测试作为运行在两个传递︰

  1. 执行安装程序︰ 测试文件中的代码从顶部到底部设置测试上下文和期望
  2. 执行︰ 每个单元测试运行,基本上每一个 it / specify 语句,用正确的安装/拆卸的代码重复每个测试

注意大部分在猕猴桃代码测试文件被指定为一系列的块发送到猕猴桃功能。任何不遵循猕猴桃块的代码模式,如您初始化/修改的代码 collection 变量,因而可能会在意想不到的时候执行。在这种情况下,所有集合修改代码正在执行期间第一次设置你的测试中,,然后运行您的测试时。

解决方案

声明 collection__block 修饰符和使用 beforeEach 来实例化并修改 collection 对象︰

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", ^{
                ...

beforeEach块告诉猕猴桃具体运行单元测试,每一次给定的代码和与嵌套的情况下,块将在序列中根据需要执行。所以猕猴桃会做这样的事情︰

// 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)]

__block修饰符将确保 collection 对象引用可以适当地保留和修改通过所有这些块功能。

官方微信
官方QQ群
31647020