Zach Lysobey
Zach Lysobey

Reputation: 15744

How to test java.sql.Timestamp is within a few milliseconds?

I'm writing a unit test, and due to some weird conversion problem between SQL server dates and java.util.Date, when I test my actual and expected dates, they are consistently 0-2ms off.

How can I assert that these dates are within just a few milliseconds of eachother?

def currentTime = new Date()

dao.recordLogin(currentTime)

def actual = dao.getLastLogin()

expect: actual == new java.sql.Timestamp(currentTime.time)

/*
  actual == new Timestamp(currentTime.time)
  |      |  |             |           |
  |      |  |             |           1381332920392
  |      |  |             Wed Oct 09 11:35:20 EDT 2013
  |      |  2013-10-09 11:35:20.392
  |      false
  2013-10-09 11:35:20.393
*/

Tried to keep the code example relatively simple. Lemme know if you want more.

Upvotes: 1

Views: 4104

Answers (2)

Gyro Gearless
Gyro Gearless

Reputation: 5279

Just take the miliseconds value and check if the difference is less than some miliseconds:

assertTrue("Login takes too long", Math.abs(currentTime.getTime() - actual.getTime()) < 5L);

Upvotes: 1

Manisha Mahawar
Manisha Mahawar

Reputation: 635

I am not sure how you are trying to convert the java.util.Date to java.sql.Timestamp while inserting into database. I wrote a very simple test just to test the conversion from one another and it seems to be asserting fine.. Here are the tests I wrote..

    @Test
    public void dateTest() {

        java.util.Date utilDate = new java.util.Date();
        java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

        assertEquals(utilDate.getTime() , sqlDate.getTime());

    }

    @Test
    public void timestampTest() {

        java.util.Date utilDate = new java.util.Date();
        java.sql.Timestamp timestamp = new java.sql.Timestamp(utilDate.getTime());

        assertEquals(utilDate.getTime() , timestamp.getTime());

    }

    @Test
public void timestampToUtilDateTest() {

    java.util.Date utilDate = new java.util.Date();
    java.sql.Timestamp timestamp = new java.sql.Timestamp(utilDate.getTime());
    java.util.Date utilDateFromTimestamp = new java.util.Date(timestamp.getTime());


    assertEquals(utilDateFromTimestamp.getTime() , timestamp.getTime());

}

I hope it helps. Thanks Manisha

Upvotes: 1

Related Questions