Mocking the LocalDateTime.Another useful class in the java. time package is the LocalDateTime class. This class represents a date-time without a timezone in the ISO-8601 calendar system. The now() method of this class allows us to get the current date-time from the system clock in the default timezone.
PowerMock is an open-source Java framework used for creating a mock object in unit testing. It extends other mocking frameworks such as EasyMock and Mockito to enhance the capabilities.
Preparing PowerMockito Extension PowerMockito uses Java Reflection API mock final, static or private methods to help Mockito to run tests using these methods. To prepare for tests, we apply two annotations at the test class level. Here Service class contains the methods to be mocked. @RunWith(PowerMockRunner.
I want to mock only the now()
of LocalDate
using PowerMock. It seems that it's ignoring the thenReturn
value:
java.lang.AssertionError:
Expected :2008
Actual :2017
Test setup:
@PrepareForTest(LocalDate.class)
@RunWith(PowerMockRunner.class)
public class UserTest {
@Test
public void nowShouldReturnSameYear() throws Exception {
LocalDate expected = LocalDate.parse("2008-04-04");
PowerMockito.spy(LocalDate.class);
when(LocalDate.now()).thenReturn(expected);
Foo foo = new Foo();
assertEquals(expected.getYear(), foo.getRightNow().getYear());
}
Foo.java
public LocalDate getRightNow(){
final LocalDate rightNow = LocalDate.now();
return rightNow;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With