FlexTradeUKLtd/jfixture

java.sql.Date cannot be parsed

Closed this issue · 1 comments

Dear Devs,

When I calling fixture.create() to a class which has java.sql.Date as a field, the following exception comes:
com.flextrade.jfixture.exceptions.ObjectCreationException: Error setting property setHours at com.flextrade.jfixture.behaviours.autoproperty.AutoPropertyPopulater.trySetProperty(AutoPropertyPopulater.java:71)

Thank you very much for your help!

Hi @MrMojoR thanks for the issue.

This isn't working for you because JFixture doesn't explicitly handle java.sql.Date objects so it uses the default resolution algorithm (try a constructor, and then call the setters), which errors because the setHours will sometimes be called with numbers > 24 (as it just picks a random int).

A simple workaround is to override this algorithm and generate a java.util.Date (which JFixture has explicit logic to handle) and create the java.sql.Date from that.

fixture.customise().lazyInstance(java.sql.Date.class, new SpecimenSupplier<java.sql.Date>() {
    @Override
    public java.sql.Date create() {
        return new java.sql.Date(fixture.create(java.util.Date.class).getTime());
    }
});

Obviously this can be much simpler with Java 8 lambdas if they're available to you,

fixture.customise().lazyInstance(java.sql.Date.class, () -> new java.sql.Date(fixture.create(java.util.Date.class).getTime()));