1

Under the following setting

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class myTest {

I have this on my src

DateFormat dataformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentdate = dataformat.format(new Date());

And I know Date.getTime() method will be called.

I tried this on my test code.

final Date date = Mockito.mock(Date.class);
Mockito.when(date.getTime()).thenReturn(dateLongValue);

But nothing happened. I also tried with mock up like this

Mockito.when(date.format(new Date())).thenReturn(dateStringValue);

But got

java.lang.NullPointerException
at java.text.DateFormat.format(DateFormat.java:346)

This could be easy but I had no luck. Any suggestion would be appreciated.

felixC
  • 91
  • 2
  • 9
  • I suspect the solution is to **not** do `dataformat.format(new Date());`. – user253751 Sep 08 '16 at 02:18
  • 2
    Check the below link it may useful http://stackoverflow.com/questions/11887799/how-to-mock-new-date-in-java-using-mockito – bhanu avinash Sep 08 '16 at 02:56
  • What exactly is the problem? Both lines of code will work in your test, there is no actual NEED to mock anything. If you want to check if this work, simply parse back currentdate and check if it's within a few ms of now...? What exactly are you trying to test? – Florian Schaetz Sep 08 '16 at 04:18

2 Answers2

1

java.time

You are using the troublesome old legacy date-time classes, now supplanted by the java.time classes.

Clock

The java.time classes let you pass alternate implementations of Clock for the purpose of testing.

Clock even comes with a few alternate implementations already built for you. One can freeze to a specific fixed moment. Another keeps time but offset a specified amount from the true time. Others increment by whole seconds, or whole minutes, or by any amount you specify.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

The "correct" way of doing this: write test-able code. And directly calling new sometimes leads to hard-to-test code. And then people need to pull out the big PowerMock(ito) hammer in order to fix that.

Alternatively, consider to learn how to write testable code; starting here.

In your case, you could give a little factory to your code under tests that generates "current" Date objects for you. You use dependency injection to get that factory into your class under test; and for testing, you mock that factory. Leading to zero need to mock calls to new.

GhostCat
  • 137,827
  • 25
  • 176
  • 248