2011-10-05 56 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]; 

比較計數確保了陣列中的一個不包含對象多次,因此確保他們真的等於。