Doing a compare of NSArray in ocUnit
Asked Answered
S

3

6

I'm new to ocUnit and I'm attempting to compare 2 arrays with the STAssertTrue method and == for equality.

The test below simply asks the system under test (sut) for the array in return

- (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 simply return the same array

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

Yet when the test runs I get a failure. How should I compare these objects to see if they are the same or not?

Thank you in advance

Snead answered 30/1, 2011 at 1:57 Comment(0)
I
2

You probably want something like:

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

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

As the other fellow said, in Objective-C, == implies pointer equality and not value equivalence.

Inspector answered 30/1, 2011 at 3:57 Comment(0)
M
3

There's a macro STAssertEqualObjects which uses -isEqual: for object comparison. I think it's exactly what you need.

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

Mining answered 30/1, 2011 at 7:39 Comment(1)
In my opinion this is a better approach than the accepted answer. If the arrays differ, the contents of both will be printed when the assert fails, which is usually helpful.Copyist
I
2

You probably want something like:

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

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

As the other fellow said, in Objective-C, == implies pointer equality and not value equivalence.

Inspector answered 30/1, 2011 at 3:57 Comment(0)
H
1

What you are comparing is whether expected and result are pointing to the same array, which they obviously are not. Instead in order to compare the content you need to go through both the NSArrays and compare object by object using the object's compare function.

Hymettus answered 30/1, 2011 at 2:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.