【问题标题】:Unit testing a fluent interface with Mockito使用 Mockito 对流畅的界面进行单元测试
【发布时间】:2015-06-13 21:45:58
【问题描述】:

我想模拟构建器模式中使用的 DAO 接口,如下所示。但是,当我在下面运行测试时,它通过表明我的模拟对象永远不会被调用。我做错了什么?

public class DBContent {
    ...

    public static class Builder {

        DAO dao = new DAO();
        ...

        public Builder callInsert() {
            ...
            long latest = dao.insert();
            ...
        }
    }
    ...
}

@RunWith(MockitoJUnitRunner.class)
public class DBContentTest {

    @Mock
    DAO dao;

    @Test
    public void test() {
        when(dao.insert()).thenReturn(1111L);
        DBContent db = DBContent.db()
                .callInsert()
                .callInsert()
                .callInsert()
                .build();
        verifyZeroInteractions(dao);
    }
}

【问题讨论】:

  • 您在测试中创建了一个模拟 DAO,但您测试的构建器不使用它。它创建了自己的 DAO。在构建构建器时,您需要将模拟 DAO 作为参数传递。了解依赖注入。

标签: java unit-testing mocking mockito builder-pattern


【解决方案1】:

改用 PowerMockito。在那里,您可以定义每当您调用 DAO 的构造函数时,返回我的模拟对象而不是返回实际的 DAO 对象。
请参考this了解如何使用PowerMockito。

【讨论】:

    猜你喜欢
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 2016-03-15
    • 1970-01-01
    相关资源
    最近更新 更多