Search code examples
objective-cunit-testingnsdecimalnumber

NSDecimalNumber unit test struggle


I am trying to write unit test for my method doing some operations on NSDecimalNumber. For simplicity I prepared this simple unit test snippet:

- (void) testTmp {
    NSDecimalNumber* val = [NSDecimalNumber decimalNumberWithString:@"0"];
    XCTAssertEqual([val stringValue], @"0");
}

Unfortunately it fails and I can't get it to work. What am I doing wrong? How do I test if NSDecimalNumber's value equals to other value?


Solution

  • XCTAssertEqual() compares the object references. You should use XCTAssertEqualObjects().

    - (void) testTmp {
      NSDecimalNumber* val = [NSDecimalNumber decimalNumberWithString:@"0"];
      XCTAssertEqualObjects([val stringValue], @"0");
    }
    

    BTW: You should not compare the string representation of the number, but the number itself …:

    - (void) testTmp {
      NSDecimalNumber* val = [NSDecimalNumber decimalNumberWithString:@"0"];
      XCTAssertEqualObjects(val, [NSDecimalNumber decimalNumberWithString:@"0"]);
    }
    

    … or (did not check it, whether NSNumber and NSDecimalNumber can be equal, but it should be that way) …

    - (void) testTmp {
      NSDecimalNumber* val = [NSDecimalNumber decimalNumberWithString:@"0"];
      XCTAssertEqualObjects(val, @0);
    }
    

    However, instances of NSDecimalNumber are floating point values. Comparing them for equity is voodoo.