junit - Java Mockito when-return on Object creation -
i'm trying test class calculates age. method calculates age looks this:
public static int getage(localdate birthdate) { localdate today = new localdate(); period period = new period(birthdate, today, periodtype.yearmonthday()); return period.getyears(); } since want junit time-independent want today variable january 1, 2016. tried going mockito.when route running trouble.
i first had this:
public class calculatortest { @before public void setup() throws exception { localdate today = new localdate(2016,1,1); mockito.when(new localdate()).thenreturn(today); } } but got error:
org.mockito.exceptions.misusing.missingmethodinvocationexception: when() requires argument has 'a method call on mock'. example: when(mock.getarticles()).thenreturn(articles); also, error might show because: 1. stub either of: final/private/equals()/hashcode() methods. methods *cannot* stubbed/verified. mocking methods declared on non-public parent classes not supported. 2. inside when() don't call method on mock on other object. so tried make method inside calculator class return current date so:
public static localdate getcurrentdate() { return new localdate(); } public static int getage(localdate birthdate) { localdate today = getcurrentdate(); period period = new period(birthdate, today, periodtype.yearmonthday()); return period.getyears(); } so this:
public class calculatortest { @before public void setup() throws exception { calculatortest mock = mockito.mock(calculatortest.class); localdate today = new localdate(2016,1,1); mockito.when(mock.getcurrentdate()).thenreturn(today); } } but exact same problem. ideas on how return predefined localdate object whenever age calculation triggered?
instead of mocking, i'd suggest using joda's datetimeutils "freeze" time. need use org.joda.time.localdate instead of java.time.localdate in application code.
public class calculatortest { @before public void setup() throws exception { datetimeutils.setcurrentmillisfixed(new localdate(2016,1,1).todatetimeatstartofday().getmillis()); } @after public void teardown() { datetimeutils.setcurrentmillissystem(); } } for pure java, consider approaches described here, particularly, injecting clock or using powermock.
injecting clock quite similar joda example; need maintain own static clock. application code this:
static clock appclock = clock.systemdefaultzone(); public static int getage(localdate birthdate) { localdate today = localdate.now(appclock); period period = new period(birthdate, today, periodtype.yearmonthday()); return period.getyears(); } and test freeze time this:
public class calculatortest { @before public void setup() { appclock = clock.fixed(localdate(2016,1,1).todatetimeatstartofday(), zoneid.systemdefault()); } @after public void teardown() { appclock = clock.systemdefaultzone(); } }
Comments
Post a Comment