Mocking Joda DateTime method using Mockito

2019-02-10 00:54发布

I want millis to return specified value.

public long myMethod(){
    DateTime nowDateTime = new DateTime(DateTimeZone.UTC);
    long millis = nowDateTime.getMillis();
    System.out.println(millis);
}

I tried this with no luck.

@RunWith(PowerMockRunner.class)
@PrepareForTest({ DateTime.class })
@PowerMockIgnore({ "javax.crypto.*", "javax.management*" })
...
...
public void testMyMethod(){
    DateTime nowDateTime = PowerMockito.mock(DateTime.class);
    Mockito.when(nowDateTime.getMillis()).thenReturn(10L);
}

How can I fix this?

1条回答
太酷不给撩
2楼-- · 2019-02-10 01:51

Just use the org.joda.time.DateTimeUtils#setCurrentMillisFixed method of JodaTime which was designed to fix new DateTime() to a different time than the current time. To return to the normal time use org.joda.time.DateTimeUtils#setCurrentMillisSystem afterwards. No mocking needed.


@Test
public void test() {
DateTimeUtils.setCurrentMillisFixed(10L);
// .. your code
}

@After
public void cleanup() {
// Make sure to cleanup afterwards
DateTimeUtils.setCurrentMillisSystem()
}

查看更多
登录 后发表回答