使用Kiwi比较两个等效对象的数组(Sentestingkit

时间:2011-10-05 21:32:43

标签: iphone objective-c bdd sentestingkit

我想比较两个等效对象的数组,一个是我班级的属性,另一个是我的测试方法。

我无法直接比较,因为对象将单独分配,因此具有不同的内存位置。

为了解决这个问题,我在我的对象上实现了描述,在字符串中列出了它的属性:(vel是CGPoint)

- (NSString *)description {
return [NSString stringWithFormat:@"vel:%.5f%.5f",vel.x,vel.y];
}

我测试:

NSLog(@"moveArray description: %@",[moveArray description]);
NSLog(@"currentMoves description: %@", [p.currentMoves description]);

[[theValue([moveArray description]) should] equal:theValue([p.currentMoves description])];

我的NSLog的收益率:

Project[13083:207] moveArray description: (
"vel:0.38723-0.92198"
)

Project[13083:207] currentMoves description: (
"vel:0.38723-0.92198"
)

但我的测试失败了:

/ProjectPath/ObjectTest.m:37: error: -[ObjectTest example] : 'Object should pass test' [FAILED], expected subject to equal <9086b104>, got <7099e004>

theValue使用字节和目标C类型初始化KWValue并使用

设置其值
- (id)initWithBytes:(const void *)bytes objCType:(const char *)anObjCType {
if ((self = [super init])) {
    objCType = anObjCType;
    value = [[NSValue alloc] initWithBytes:bytes objCType:anObjCType];
}

return self;
}

如何比较这两个数组是否具有等效值的对象?

2 个答案:

答案 0 :(得分:3)

您的测试失败,因为您正在比较指针地址,而不是值。

您可以迭代一个数组,并将每个对象与第二个数组中等效定位的对象进行比较。确保您正在比较的值类型正确完成比较。如果每个元素都有不同的类型,那么它会变得更加棘手。

// in some class
- (BOOL)compareVelocitiesInArray:(NSArray *)array1 withArray:(NSArray *)array2
{
    BOOL result = YES;

    for (uint i = 0; i < [array1 count]; i++) {
        CustomObject *testObj1 = [array1 objectAtIndex:i]
        CustomObject *testObj2 = [array2 objectAtIndex:i]

        // perform your test here ...
        if ([testObj1 velocityAsFloat] != [testObj2 velocityAsFloat]) {
            result = NO;
        }
    }

    return result;
}

// in another class
NSArray *myArray = [NSArray arrayWithObjects:obj1, obj2, nil];
NSArray *myOtherArray = [NSArray arrayWithObjects:obj3, obj4, nil];
BOOL result;

result = [self compareVelocitiesInArray:myArray withArray:myOtherArray];
NSLog(@"Do the arrays pass my test? %@", result ? @"YES" : @"NO");

答案 1 :(得分:0)

将两个数组的内容与Kiwi进行比较的另一种可能性:

[[theValue(array1.count == array2.count) should] beTrue];
[[array1 should] containObjectsInArray:array2];
[[array2 should] containObjectsInArray:array1];

比较计数可确保其中一个数组不多次包含一个对象,因此确保它们真的相等。