在 junit 测试中模拟 DateFormat 类

hen*_*rik 4 java junit unit-testing mockito

我正在尝试模拟 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");
    }
}
Run Code Online (Sandbox Code Playgroud)

给出以下错误:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException:参数匹配器的使用无效!预计 3 名匹配者,记录 1 名:

-> 在 someTest.before(someTest.java:33)

如果匹配器与原始值组合,则可能会出现此异常: //in Correct: someMethod(anyObject(), "raw String"); 使用匹配器时,所有参数都必须由匹配器提供。例如: //正确:someMethod(anyObject(), eq("String by matcher"));

有关详细信息,请参阅 Matchers 类的 javadoc。

在 java.text.DateFormat.format(来源未知)
在 someTest.before(someTest.java:33)

如何以正确的方式模拟 DateFormat 类?

Ser*_*hyr 5

问题在于实施format(Date date)

public final String format(Date date) {
    return format(date, new StringBuffer(),
                  DontCareFieldPosition.INSTANCE).toString();
}
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,它是最终的。Mockito 无法模拟最终方法。相反,它将调用真正的方法。作为解决方法,您可以模拟方法format(date, new StringBuffer(), DontCareFieldPosition.INSTANCE)

when(formatter.format(any(Date.class), any(StringBuffer.class), 
                      any(FieldPosition.class)))
    .thenReturn(new StringBuffer("2017-02-06"));
Run Code Online (Sandbox Code Playgroud)

因此,当方法format(date)调用您的模拟方法时,结果将如您所料。