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?