我如何模拟 java.time.LocalDate.now() [英] How can I mock java.time.LocalDate.now()
问题描述
在我的测试用例中,我需要测试时间敏感的方法,在该方法中我们使用的是 java 8 类 LocalDate,它不是 Joda.
In my test case, I need test time sensitive method, in that method we're using java 8 class LocalDate, it is not Joda.
我可以做些什么来改变时间,当我运行测试时
What can I do to change time, when I'm running test
推荐答案
在您的代码中,将 LocalDate.now()
替换为 LocalDate.now(clock);
.
In your code, replace LocalDate.now()
with LocalDate.now(clock);
.
然后您可以传递 Clock.systemDefaultZone()
用于生产和 一个固定时钟用于测试.
You can then pass Clock.systemDefaultZone()
for production and a fixed clock for testing.
这是一个例子:
首先,注入Clock
.如果您使用的是弹簧靴,只需执行以下操作:
First, inject the Clock
. If you are using spring boot just do a :
@Bean
public Clock clock() {
return Clock.systemDefaultZone();
}
其次,在您的代码中调用 LocalDate.now(clock)
:
Second, call LocalDate.now(clock)
in your code :
@Component
public class SomeClass{
@Autowired
private Clock clock;
public LocalDate someMethod(){
return LocalDate.now(clock);
}
}
现在,在您的单元测试类中:
Now, inside your unit test class :
// Some fixed date to make your tests
private final static LocalDate LOCAL_DATE = LocalDate.of(1989, 01, 13);
// mock your tested class
@InjectMocks
private SomeClass someClass;
//Mock your clock bean
@Mock
private Clock clock;
//field that will contain the fixed clock
private Clock fixedClock;
@Before
public 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();
}
@Test
public void testSomeMethod(){
// call the method to test
LocalDate returnedLocalDate = someClass.someMethod();
//assert
assertEquals(LOCAL_DATE, returnedLocalDate);
}
这篇关于我如何模拟 java.time.LocalDate.now()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!