2011-10-05 58 views
0

我想比较两个数组的等效对象,其中一个属性在我的类中,另一个在我的测试方法中。比较两个阵列的等效对象与Kiwi(Sentesting)套件

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

为了解决这个问题,我实现我的目标字符串中,列出其属性的描述:(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初始化与字节KWValue和物镜-C型,并将其值与

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

return self; 
} 

如何可以比较这两个阵列具有等价的值的对象?

回答

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"); 
+0

完美,谢谢。欢迎来到SO! – quantumpotato

+0

谢谢,很高兴我能帮上忙。 – Sticktron

0

另一种可能性,以两个数组平等内容比较猕猴桃:

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

比较计数确保了阵列中的一个不包含对象多次,因此确保他们真的等于。