1

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?

haoyu wang
  • 1,241
  • 4
  • 17
  • Does this answer your question? [Using PowerMockito.whenNew() is not getting mocked and original method is called](https://stackoverflow.com/questions/25317804/using-powermockito-whennew-is-not-getting-mocked-and-original-method-is-called) – racraman May 09 '22 at 10:51

1 Answers1

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

Kai-Sheng Yang
  • 1,535
  • 4
  • 15
  • 21