我使用Powermock和Easymock对我的代码进行单元测试。我有一个方法在内部调用返回Entity Manager对象的方法(由spring初始化)。 如何从junit代码中模拟此函数? 还有其他方法吗? 目前我编写的代码看起来像这样
BaseJpaDaoImpl jpaDaoImplMock= EasyMock.createNiceMock(BaseJpaDaoImpl.class);
EasyMock.expect(jpaDaoImplMock.getEntityManager(true)).andReturn().anyTimes();
EasyMock.replay(jpaDaoImplMock);
BaseJpaDaoImpl包含返回Entity Manager实例的方法。
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);
答案 0 :(得分:0)
最后,在经历了很多崩溃后,我意识到我错过了一个小点。 这就是我所做的
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);
简单地嘲笑我的回应
不是最好的技术,但我得到了我想要的东西。
感谢所有试过的人!!