java: how to mock Calendar.getInstance()?

前端 未结 6 926
忘了有多久
忘了有多久 2020-12-03 16:54

In my code I have something like this:

private void doSomething() {
   Calendar today = Calendar.getInstance();
   ....
}

How can I \"mock\

6条回答
  •  盖世英雄少女心
    2020-12-03 17:16

    Write a class called DateHelper with a method getCalendar that returns Calendar.getInstance(). Refactor the class that you're testing so that it has a member variable of type DateHelper, and a constructor that injects that member variable. Use that constructor in your test, to inject a mock of DateHelper, in which getCalendar has been stubbed to return some known date.

提交回复
热议问题