Search code examples
sqloracle-databaseunit-testingdatedbunit

Create a date, insert it into database, compare, it's different


The goal

I've got a really strange problem. My goal is to compare a dynamic date in database using dbunit (the database is an Oracle one). This dynamic date is the today date (comparing static date works...)

The experimentation

To compare date, I use this very simple code :

@Test
public void simpleDateTest() throws DatabaseUnitException, SQLException {
    // create a date corresponding to today
    Date today = new Date();

    // load a dataset
    IDataSet expectedDataSet = new FlatXmlDataSetBuilder().build(getClass()
            .getResource("/dataset.xml"));

    // replace [TODAY] by the today date
    ReplacementDataSet rDataSet = new ReplacementDataSet(expectedDataSet);
    rDataSet.addReplacementObject("[TODAY]", today);

    // insert the dataset
    DatabaseConnection connection = getConnection();
    DatabaseOperation.CLEAN_INSERT.execute(connection, rDataSet);

    // do a simple query to get some fields, em is the entity manager which uses the same connection as above
    Query q = em
            .createNativeQuery("SELECT ID, MY_DATE FROM MY_TABLE");
    List<Object[]> result = q.getResultList();

    // compare the date with today date
    assertEquals(today.getTime(), ((Date) result.get(0)[1]).getTime());
}

With the following dataset :

<?xml version='1.0' encoding='UTF-8'?>
<dataset>
    <MY_TABLE ID="1" MY_DATE="[TODAY]" />
</dataset>

The problem

I don't know why, but the assert failed ! When comparing the two dates, there is a very few milliseconds difference. The error is something like that :

java.lang.AssertionError: expected:<1358262234801> but was:<1358262234000>

I don't understand how is it possible to have different dates because they are quite normally the same ! Any clue to understand the problem and how to solve it ?


Solution

  • The Oracle Date type doesn't have a resolution of milliseconds, it only has a resolution of seconds.
    When saving a time to the database the milliseconds are simply stripped off. When you look at the actual value you see that the last three digits are all zero.