Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Mock only LocalDate.now() using PowerMock

Tags:

People also ask

Can we mock LocalDateTime in Java?

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.

What is PowerMock in Mockito?

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.

How do you use PowerMockito?

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;
    }