Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDate Compare in tests

I'm writing some tests to see if a person object is correctly saved into a local database (SQLite, using strings for the dates).

in my tests I have :

let testPerson = Person(firstName:"John", lastName:"Doe")

After saving to the database I test if createdAt != nil

That is ok! Then :

let testPerson2 = Person.LoadByID(testPerson.id)

which is a static function loading a person object from the database into testPerson2

all fields are passing in the tests (so they're exactly the same for testPerson and testPerson2 except the createdAt and updateAt dates

If I do a println of those dates, they're EXACTLY the same :

testPerson.createdAt : Optional(2015-08-14 12:03:01 +0000)
testPerson2.createdAt :Optional(2015-08-14 12:03:01 +0000)

But testing (via 2 different methods):

XCTAssert(testPerson2.createdAt == testPerson.createdAt, "createdAt should be the same")

or

XCTAssertTrue(testPerson2.createdAt!.isEqualToDate(testPerson2.createdAt!), "createdAt should be the same")

fail

Doing those tests with 2x testPerson or testPerson2, succeeds

I also tried the following code:

if testPerson.createdAt!.compare(testPerson.createdAt!) == NSComparisonResult.OrderedDescending
        {
            println("date1 after date2");
        } else if testPerson.createdAt!.compare(testPerson.createdAt!) ==     NSComparisonResult.OrderedAscending
        {
            println("date1 before date2");
        } else
        {
            println("dates are equal");
        }

failing if I use testPerson and testPerson2, succeeding with testPerson/testPerson and testPerson2/testPerson2

Why ? Println and looking into the database itself look ok.

like image 283
Glenn Avatar asked Feb 10 '26 19:02

Glenn


1 Answers

Internally NSDate has a resolution of at least one nanosecond. Your dateFormatter removes most of that resolution because the dateformat ss.SSS only handles milliseconds.

If you don't need a nanosecond precision I would recommend to only check your dates up to the millisecond level. I usually use XCTAssertEqualWithAccuracy() for that.

e.g.:

XCTAssertEqualWithAccuracy(date1.timeIntervalSinceReferenceDate,
                           date2.timeIntervalSinceReferenceDate,
                           0.001, 
                           "")
like image 104
Matthias Bauch Avatar answered Feb 12 '26 14:02

Matthias Bauch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!