我试图测试一个计算年龄的类。计算年龄的方法是这样的: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