Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

As part of Java code some task needs to be done tomorrow in JUnit.

For example there are 3 tasks:

  • task1 - done
  • task2 - do it tomorrow
  • task3 - then this will happen

So as per requirement I need to set today's date as tomorrow in Java.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
186 views
Welcome To Ask or Share your Answers For Others

1 Answer

The root of your problem is that the system clock (what gives you the time in a new Date ()) is not giving you the time you need for your test.

You can avoid this problem by introducing a level of indirection. Instead of having your code directly ask the Java API what the current time is, you have your code ask a Clock object what the time is. In the real program your Clock implementation uses the system clock. For your unit tests you use a FakeClock, which says whatever time you want it to. You tell your code what Clock to use using dependency injection. You have to write the Clock interface (or abstract base class) and its concrete implementations yourself.

This approach requires you to alter your existing code, so it is easier to test. Or write it in the first place so it is easier to test. It's one of the tricks of unit testing.

I'm working on some code at the moment that is time sensitive. My clock interface is simply

 public interface Clock {
    long getCurrentTime ();
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...