【发布时间】: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