Search code examples
objective-cunit-testingocunit

What is the difference between STAssertEqualObjects and STAssertEquals?


I have the following class:

#import "Period.h"

@implementation Period

...

- (BOOL)isEqualTo:(id)object {
    return [self isEqual:object];
}

- (BOOL)isEqual:(id)object {

    if (object == self) {
        return YES;
    }

    if ([[object beginDate] hash] == [[self beginDate] hash] &&
        [[object endDate] hash] == [[self endDate] hash]) {
        return YES;
    }

    return NO;
}

...

@end

And also the following test, written using OCUnit:

Period *period;
NSDate *beginDate;
NSDate *endDate;

- (void)setUp {
    beginDate = [NSDate dateWithString:@"2011-02-25"];
    endDate = [NSDate dateWithString:@"2011-03-25"];

    period = [[Period alloc] initWithBeginDate:beginDate
                                       endDate:endDate];
}

- (void)testEndDateShouldBeGreaterOrEqualThanBeginDate {
    Period *newPeriod = [[Period alloc] initWithBeginDate:beginDate
                                                  endDate:beginDate];

    STAssertEqualObjects(beginDate, [newPeriod beginDate], @"Begin dates are different");
    STAssertEqualObjects(endDate, [newPeriod endDate], @"End dates are different");
}

Previously I was using STAssertEquals instead of STAssertEqualObjects and it was not calling isEqual method on Period.

I just want to understand two things:

  • What's the difference between those two methods?
  • What's the difference between isEqual and isEqualTo?

Solution

  • STAssertEquals compares the raw bytes that make up the two parameters that are passed to it, and is intended to be used with scalar types (float, int, char, etc.), structs or unions---you should not use it to compare Objective-C objects. STAssertEqualObjects compares two Objective-C objects by calling isEqual:.

    isEqualTo: is used to support NSSpecifierTest (refer to the NSComparisonMethods Protocol Reference). It is unnecessary to provide an implementation for isEqualTo: if your objects aren't scriptable.