'use Powermock mock new Date() does not work as expected

I want to mock constructor of Date object. But it doesn't work as I expected.
suppose I have such a service.

public class TestService {
    public Date getNewDate(){
        return new Date();
    }
}

And I write folloing test

@Test
void test3() throws Exception {
    TestService testService=new TestService();
    Date mockDate = new Date(120, 1, 1);
    PowerMockito.mock(Date.class);
    PowerMockito.whenNew(Date.class).withNoArguments().thenReturn(mockDate);
    Assertions.assertEquals(mockDate,new Date()); //succeed
    Assertions.assertEquals(mockDate,testService.getNewDate()); //failed

}

result is:

org.opentest4j.AssertionFailedError:
Expected :Sat Feb 01 00:00:00 CST 2020
Actual :Mon May 09 18:35:05 CST 2022

After mock ,I am excepting the service will return the mockDate object. But it's not. And the interesting thing is, if I call new Date in the test rather than in the service, I get the right result.
Why is it?



Solution 1:[1]

You must add @PrepareForTest annotation to your test class when you are using PowerMockito.whenNew.

 @RunWith(PowerMockRunner.class)
 @PrepareForTest(TestService.class)
 public class YourTest {
     
    @Test
    void test3() throws Exception {
        // ...
    }

 }

You can find more about @PrepareForTest here: https://stackoverflow.com/a/56430390/5485454

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kai-Sheng Yang