Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Unit Testing method that uses new Date() for current date [duplicate]

So I have a class that has a method "getDaysUntil(Date date)" which returns the number of days until the date given as parameter. I mention that I cannot change the class below:

public class A {

public int getDaysUntil(Date givenDate) {

    ... // code

    Date currentDate = new Date() //it creates a date object holding the current day

    ...// code that calculates the nr of days between currentDate and givenDate.

}

I have to do some unit testing and you might see the problem, it creates currentDate inside the method and the returned value will be different from day to day. I have tried to mock a Date object or "override" System.currentTimeMillis() with PowerMock but to no avail.

Is there any way to properly test these kind of methods?

like image 262
Vlad Dobrieski Avatar asked Mar 03 '17 07:03

Vlad Dobrieski


2 Answers

Use a class that serves as a DateFactory, which is called to construct Date objects in your application code.

Then just mock the method of that DateFactory in your unit test. That way you can make it return whatever date you want as a virtual "current date"

like image 156
Jens Wurm Avatar answered Sep 19 '22 21:09

Jens Wurm


One solution where System.currentTimeMillis() is mocked is as follows, using the JMockit library (it should be possible with PowerMock too):

@Test @SuppressWarnings("deprecation")
public void daysUntilCurrentDate() {
    final long fakeCurrentDateInMillis = new Date(2017, 2, 1).getTime();
    new MockUp<System>() {
        @Mock long currentTimeMillis() { return fakeCurrentDateInMillis; }
    };
    A tested = new A();

    int daysSinceJan30 = tested.getDaysUntil(new Date(2017, 1, 30));

    assertEquals(2, daysSinceJan3O);
}
like image 27
Rogério Avatar answered Sep 16 '22 21:09

Rogério