2

While testing the updating of an entity, I want to also make sure that the dates are working correctly. In my entity I have:

@PreUpdate
private void onUpdate() {
    this.lastUpdated = new LocalDateTime();
}

When I test a brand getting updated, I'm created the brand, modifying it, then calling update, after-which I refetch the brand to assert I could find it by the changed value.

The time between saving and updating is often so small, the dates end up being the same:

assertThat(first.getLastUpdated().isBefore(brand.get().getLastUpdated())).isEqualTo(true);

I've solved this currently by adding in a Thread.sleep(100) call between the save and update, but my gut says this is a really bad idea. Thoughts?

Gregg
  • 34,973
  • 19
  • 109
  • 214
  • 1
    i would take a look at this, and restructure my code, as the accepted answer suggests. http://stackoverflow.com/questions/11887799/how-to-mock-new-date-in-java-using-mockito Secondly, you should be able to assume that `@PreUpdate` is working as intended, and if you want to make sure your method is annotated, make a small unit test to verify this. You could also let the database handle the _on update_ (i would actually prefer this myself) if it supports it – Martin Hansen Dec 21 '16 at 09:39

2 Answers2

0

If you are using Java 8, it would be cleaner to inject a Clock collaborator, which you could control for your tests.

Jamie Bisotti
  • 2,605
  • 19
  • 23
0

In general I think yes, its a bad idea.

The tests (including integration tests of course) have to be as fast as possible. If you have a descent code base and a descent amount of integration tests, many sleeps like this can cost minutes or even hours. If you're running Continuous Integration, it can be a significant issue because you'll want a fast build.

When it comes to dates, it better to use some mock that will run instead of real code inside your code. It really depends on how exactly you work with Dates to provide a good example. Usually it requires refactoring of your code in these specific areas.

The good news that usually most of code like this would be probably covered by Unit tests at all, so you won't need a complicated setup. Probably you'll have much less integration tests, maybe one or two for a component.

halfer
  • 19,824
  • 17
  • 99
  • 186
Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97