java - 在 junit 测试中模拟 DateFormat 类

标签 java unit-testing junit 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");
    }
}

给出以下错误:

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/

相关文章:

java - 如何使用 phantomjs 将多个 web 元素传递到页面

java - 我的 JBoss 服务器在 Linux 上达到 100% SYS CPU;什么会导致这个?

java - 1ms Java 定时器延迟是否太快?

perl - 我如何将 Perl 的 'prove' 与其他语言的 TAP 生产者一起使用?

java - Lock.tryLock超时异常的JUnit测试场景

java - 如何在Java中读取、更新、插入、删除对象到txt文件

unit-testing - 单元测试和数据库

unit-testing - Kapt generatetubs - 无法使用单元测试中的内部构造函数初始化对象

java - 用于将 UTC 转换为 EST 的 JUnit 测试用例

java - 为什么 Hibernate Session 会有这样的行为