iphoneobjective-cbddsentestingkit

Comparing two arrays for equivilant objects with Kiwi (Sentesting) Kit


I want to compare two arrays for equivalent objects, one a property inside my class and the other in my test method.

I cannot compare directly since the objects will be allocated seperately and thus have different memory locations.

To get around this I implemented description on my object to list out its properties in a string: (vel is a CGPoint)

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

I test with:

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

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

My NSLog's yield:

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

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

But my test fails:

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

theValue initializes a KWValue with bytes and an objective-C type and sets its value with

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

return self;
}

How can I compare that these two arrays have objects of equivalent values?


Solution

  • Your test fails because you are comparing pointer addresses, not values.

    You can iterate through one array and compare each object against the equivalently positioned object in the second array. Make sure your comparison is done correctly for the type of value you are comparing. If every element has a different type then it gets trickier.

    // 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");