【问题标题】:Can't mock the Entity Manager function call无法模拟实体管理器函数调用
【发布时间】:2023-03-14 10:50:02
【问题描述】:

我正在使用 Powermock 和 Easymock 对我的代码进行单元测试。我有一种方法在内部调用返回 Entity Manager 对象(由 spring 初始化)的方法。 如何从我的 junit 代码中模拟这个函数? 还有其他方法吗? 目前我已经编写了一个看起来像这样的代码

BaseJpaDaoImpl jpaDaoImplMock= EasyMock.createNiceMock(BaseJpaDaoImpl.class);
EasyMock.expect(jpaDaoImplMock.getEntityManager(true)).andReturn().anyTimes();
EasyMock.replay(jpaDaoImplMock);

BaseJpaDaoImpl 包含返回实体管理器实例的方法。

protected EntityManager getEntityManager(boolean throwExceptionIfNotSet) {
    if(throwExceptionIfNotSet && entityManager == null) {
        logger.error("EM is NULL");
        throw new IllegalStateException("Deployment Issue, EM is Null!");
    }
    return entityManager;
}

看起来像这样

任何帮助将不胜感激 非常感谢!!

附加测试类

@RunWith(PowerMockRunner.class)
@PrepareForTest({RequestContextHelperUtil.class, BaseJpaDaoImpl.class,SearchAwareBaseJpaDaoImpl.class})
public class InventoryDaoJpaImplTest {

@Test
public void ABC() throws Exception {

    PowerMock.mockStatic(RequestContextHelperUtil.class);
    BaseJpaDaoImpl jpaDaoImplMock= EasyMock.createNiceMock(BaseJpaDaoImpl.class);
    EasyMock.expect(jpaDaoImplMock.getEntityManager(true)).andReturn(null).anyTimes();
    EasyMock.replay(jpaDaoImplMock);

【问题讨论】:

  • 你能展示你的整个测试类,或者至少是它的开始(类定义+注释)吗?
  • 在 andReturn() 方法中,我需要获取一个对象才能真正返回某些内容并对其进行模拟

标签: unit-testing junit easymock powermock


【解决方案1】:

最后,经过一番头疼后,我意识到我错过了一个小点。 这就是我所做的

EntityManager em = EasyMock.createNiceMock(EntityManager.class);
BaseJpaDaoImpl jpaDaoImplMock = EasyMock.createNiceMock(BaseJpaDaoImpl.class);
EasyMock.expect(jpaDaoImplMock.getEntityManager(true)).andReturn(em).anyTimes();
EasyMock.replay(em);
EasyMock.replay(jpaDaoImplMock);

只是嘲笑我的回应

不是最好的技术,但我得到了我想要的。

感谢所有尝试过的人!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-01
    • 2015-01-24
    • 2018-09-15
    • 1970-01-01
    • 2014-01-02
    • 2019-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多