Performing an NSArray comparison in ocUnit

I am new to ocUnit and I am trying to compare 2 arrays with the STAssertTrue and == method for equality.

The below test just queries the system under test (sut) for the returned array

- (void) testParse { SomeClassForTesting* sut = [[SomeClassForTesting alloc] init]; NSArray* result = [sut parseAndReturn]; NSArray* expected = [[NSArray alloc] initWithObjects:@"1", @"2", @"3", @"4",nil]; STAssertTrue(result == expected, @"This test failed"); } 

Then inside my production code I just return the same array

 - (NSArray *)parseAndReturn { NSArray* x = [[NSArray alloc] initWithObjects:@"1", @"2", @"3", @"4",nil]; return x; } 

But when the test passes, I get a failure. How to compare these objects to make sure they are the same or not?

Thank you in advance

+6
objective-c unit-testing ocunit
source share
3 answers

You probably want something like:

 STAssertTrue([result isEqual: expected], @"This test failed"); 

This will go through arrays and return false if each element does not return true from its isEqual implementations. If your array members are NSStrings as indicated, you should be kind.

As another person said, in Objective-C, == implies pointer equality, not value equivalence.

+2
source share

There's a STAssertEqualObjects macro that uses -isEqual: to compare objects. I think this is exactly what you need.

STAssertTrue in your case compares object pointers and fails, because result and expected are different objects (their pointers are different).

+3
source share

What you are comparing is that the expected and the result point to the same array, which obviously is not. Instead, to compare content, you need to go through NSArrays and compare the object by object using the object comparison function.

+1
source share

All Articles