-3

I am currently have a requirement where in, need to mock new Date() to a specific date for all the test cases.

@Before
public void setUp() throws Exception {
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   Date NOW = sdf.parse("2015-09-26 00:00:00");
   whenNew(Date.class).withAnyArguments().thenReturn(NOW);
}

So i used the above code to mock it , but still when i see the output of the test results, i could still see the actual "new Date()" is executed.

So i added this in @before block in all the test files. So can you please help to know if I am missing anything?

  • 4
    Since you're using Java 8, the preferred approach is to inject a `Clock` object; this is exactly why the API was developed. – chrylis -cautiouslyoptimistic- Oct 08 '18 at 15:02
  • 2
    See https://stackoverflow.com/questions/27067049/unit-testing-a-class-with-a-java-8-clock for more information on how to use `Clock` so that unit testing is easier. – Wim Deblauwe Oct 08 '18 at 15:08
  • 1
    As I understand, the code you are testing is using `Date`. That’s unfortunate since the class is long outdated and poorly designed. You will want to use [java.time, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) instead. It’s so much nicer to work with, though of course I cannot tell how fast you can afford to migrate. Among many nice features the modern API has good support for unit testing so you won’t need mocking anymore. – Ole V.V. Oct 08 '18 at 15:27
  • To the extent that you cannot replace the `Date` class yet you may use `Date.from(Instant.now(yourClockForTestingOrTheRealClock))`. – Ole V.V. Oct 08 '18 at 15:29
  • A) we would need a [mcve] B) most likely, you are simply not following the required steps to mock `new()` ... as the answer points out, you simply have to specific things to get it to work (which are all nicely documented btw) – GhostCat Oct 15 '18 at 06:33

1 Answers1

2

The classes under test (where new Date() is being called) need to be prepared for testing (because PowerMockito needs to do bytecode manipulation to intercept the constructor calls).

See the documentation for the @PrepareForTest annotation

Also this page has a good overview on how to do this

OhleC
  • 2,821
  • 16
  • 29