在您的代码中,将替换
LocalDate.now()为
LocalDate.now(clock);。
然后
Clock.systemDefaultZone(),您可以通过生产并使用固定时钟进行测试。
这是一个例子:
首先,注入
Clock。如果您使用的是Spring Boot,请执行以下操作:
@Beanpublic Clock clock() { return Clock.systemDefaultZone();}其次,
LocalDate.now(clock)输入您的代码:
@Componentpublic class SomeClass{ @Autowired private Clock clock; public LocalDate someMethod(){ return LocalDate.now(clock); }}现在,在单元测试类中:
// Some fixed date to make your testsprivate final static LocalDate LOCAL_DATE = LocalDate.of(1989, 01, 13);// mock your tested class@InjectMocksprivate SomeClass someClass;//Mock your clock bean@Mockprivate Clock clock;//field that will contain the fixed clockprivate Clock fixedClock;@Beforepublic void initMocks() { MockitoAnnotations.initMocks(this); //tell your tests to return the specified LOCAL_DATE when calling LocalDate.now(clock) fixedClock = Clock.fixed(LOCAL_DATE.atStartOfDay(ZoneId.systemDefault()).toInstant(), ZoneId.systemDefault()); doReturn(fixedClock.instant()).when(clock).instant(); doReturn(fixedClock.getZone()).when(clock).getZone();}@Testpublic void testSomeMethod(){ // call the method to test LocalDate returnedLocalDate = someClass.someMethod(); //assert assertEquals(LOCAL_DATE, returnedLocalDate);}


