我正在尝试模拟 DateFormat 类,因为它在我的单元测试范围内没有任何用处。我正在使用 org.mockito.Mockito 库。
以下代码:
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.any;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.junit.Before;
public class someTest {
@Mock
DateFormat formatter;
@Before
public void before() {
MockitoAnnotations.initMocks(this);
when(formatter.format(any(Date.class))).thenReturn("2017-02-06");
}
}
给出以下错误:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers! 3 matchers expected, 1 recorded:
-> at someTest.before(someTest.java:33)
This exception may occur if matchers are combined with raw values: //incorrect: someMethod(anyObject(), "raw String"); When using matchers, all arguments have to be provided by matchers. For example: //correct: someMethod(anyObject(), eq("String by matcher"));
For more info see javadoc for Matchers class.
at java.text.DateFormat.format(Unknown Source)
at someTest.before(someTest.java:33)
如何以正确的方式模拟 DateFormat 类?
最佳答案
问题在于 format(Date date)
的实现
public final String format(Date date) {
return format(date, new StringBuffer(),
DontCareFieldPosition.INSTANCE).toString();
}
如您所见,这是最终的。 Mockito 不能模拟 final 方法。相反,它将调用真正的方法。
作为解决方法,您可以模拟方法 format(date, new StringBuffer(), DontCareFieldPosition.INSTANCE)
when(formatter.format(any(Date.class), any(StringBuffer.class),
any(FieldPosition.class)))
.thenReturn(new StringBuffer("2017-02-06"));
因此,当方法 format(date)
调用您的模拟方法时,结果将如您所料。
关于java - 在 junit 测试中模拟 DateFormat 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42068239/