Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking Joda DateTime method using Mockito

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?

like image 907
shankshera Avatar asked Oct 13 '14 15:10

shankshera


1 Answers

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()
}

like image 169
Leonard Brünings Avatar answered Sep 28 '22 01:09

Leonard Brünings