Thursday, July 17, 2008

Matching JAXB Dates in Tests

If you find yourself wanting to correctly generate the date format used by JAXB, most likely in test code, you might find yourself messing with an XMLGregorianCalendar doing something like this:

        GregorianCalendar gregorian = new GregorianCalendar();
        gregorian.setTime( date );
        XMLGregorianCalendar xml = DatatypeFactory.newInstance().newXMLGregorianCalendar( gregorian );
        return xml.toXMLFormat();

If you do, you're likely to get bitten by the fact that on dates with 0 milliseconds, your method will include the milliseconds and the JAXB output will not:

expected:<2008-07-16T15:15:51[]-04:00> but was:<2008-07-16T15:15:51[.000]-04:00>

As a result, you'll want to employ code more like this:
        GregorianCalendar gregorian = new GregorianCalendar();
        gregorian.setTime( date );
        return DatatypeConverter.printDateTime( gregorian );

Et voila.

No comments: