我試圖測試一個計算年齡的類。計算年齡的方法是這樣的:Java Mockito何時返回創建對象
public static int getAge(LocalDate birthdate) {
LocalDate today = new LocalDate();
Period period = new Period(birthdate, today, PeriodType.yearMonthDay());
return period.getYears();
}
因爲我想了JUnit是時間無關我想today
變量始終是2016年1月1日,爲了做到這一點,我試圖去了Mockito.when
路線,但我遇到了麻煩。
我第一次有這樣的:
public class CalculatorTest {
@Before
public void setUp() throws Exception {
LocalDate today = new LocalDate(2016,1,1);
Mockito.when(new LocalDate()).thenReturn(today);
}
}
但是到我得到這個錯誤:
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
於是我試圖讓計算器類中的方法返回當前的日期,像這樣:
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();
}
,這樣我可以做到這一點:
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);
}
}
但是,我得到了完全相同的問題。那麼,有關如何在觸發年齡計算時返回預定義的本地對象的任何想法?
你試過從'getCurrentDate'刪除'static'修改? Mockito不能模擬靜態方法。 – user3707125