【问题标题】:Unable to Mock EntityManager Criteria API无法模拟 EntityManager 标准 API
【发布时间】:2021-02-23 03:59:22
【问题描述】:

我想为 EntityManager 编写 junit,但无法模拟 EntityManager。我的服务类方法如下:

@PersistenceContext
private EntityManager em;

public List<Items> getItems() {
    Order order = Order.desc("ASC");
    Criteria crit = em.unwrap(Session.class).createCriteria(Items.class);
    Criteria critRowCount = em.unwrap(Session.class).createCriteria(Items.class);
    crit.add(Restrictions.eq("createdBy", "John"));
    critRowCount.add(Restrictions.eq("createdBy", "John"));

    crit.setFirstResult((pageNo - 1) * pageSize);
    crit.setMaxResults(pageSize);
    crit.addOrder(order);
    List<Items> items = crit.list();
    critRowCount.add(Restrictions.sqlRestriction("Query"));

    critRowCount.setProjection(Projections.rowCount()).uniqueResult();
    return items;
}

我在我的口味中使用过:

@MockBean
private EntityManager em;

当我在服务中调用下面的方法时

List<Items> items = crit.list();

这将击中 DB。请帮我解决问题。

提前致谢!

【问题讨论】:

    标签: java spring-boot unit-testing junit junit5


    【解决方案1】:

    我不知道为什么模拟不起作用(根据您在此处介绍的内容,我认为它应该起作用)。但我想建议另一种方法。我想getItems() 方法驻留在某种存储库或DAO 或任何你称之为此类的东西中。对于单元测试,我通常会嘲笑它们。如果我想测试getItems(),我实际上会尝试在集成测试中通过数据库(例如通过testcontainers)对其进行测试,因为无论如何这都非常接近数据库。

    在您的具体情况下,我什至可能不会尝试测试 getItems(),因为它似乎只包含一些管道代码。

    根据经验:嘲笑你不拥有的东西通常不是一个好主意。

    【讨论】:

    • 感谢您的澄清。 getItems() 正在使用中,我想模拟 em.unwrap(Session.class) 以便我们可以返回自定义 Criteria 对象。类似于:doReturn(criteria).when(em).unwrap(Session.class).createCriteria(Items.class);
    猜你喜欢
    • 2014-12-17
    • 1970-01-01
    • 2012-09-22
    • 1970-01-01
    • 2014-06-16
    • 2019-06-25
    • 2011-05-16
    • 2021-02-01
    • 2015-03-27
    相关资源
    最近更新 更多