'Disable @CreationTimestamp in testing class

So I'm using Hibernate's annotations @CreationTimestamp and @UpdateTimestamp. It works fine, but I have this case when unit testing where I need to create objects in specific dates.

I think it is not possible to deactivate this annotations so the first thing I thought was remove them and do something like this:

@PrePersist
public void prePersist() {
    if (createdDate == null) {
        createdDate = new Date();
    }
}

I don't like it this way because I'll have to do a refactor of my entities just for one test case.

The other solution I think it can be better is to create an sql file with the data I need and execute it with Spring before when running my tests.

What do you think is the best way to do this?



Solution 1:[1]

Don't change your production code just for a test case. Just modify the creation date attribute on your test objects?

Solution 2:[2]

I've encountered the same problem in tests, the best solution that I came up with is: Mock static method in Clock.systemUTC so it will return Clock.fixed()

try (MockedStatic<Clock> utilities = Mockito.mockStatic(Clock.class)) {
                utilities.when(Clock::systemUTC)
                        .thenReturn(Clock.fixed(Instant.parse("2018-08-22T10:00:00Z"), ZoneOffset.UTC));
                System.out.println(Instant.now()) //here perform actions in past
            }
    System.out.println(Instant.now()) // here perform in current time

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mick
Solution 2 Vadym Ozarynskyi