我是单元测试的新手,有一些要求模拟DAO层但没有得到如何做到这一点。 下面是我的示例DAO代码,它正在进行一些事务性活动。
Class DAOList{
public Object getRows(Map mapObj, Object error) {
Session session = HibernateSessionManager.getSessionFactory().openSession();
try {
Query query = session.createSQLQuery("select * from some_table ").addEntity(SomeObject.class);
Object getObj = query.uniqueResult();
return getObj;
}
catch (HibernateException exc) {
exc.printStackTrace();
logger.error("Exception occurred: " + exc.getMessage());
}
finally {
session.close();
}
return null;
} }
我尝试编写如下所示的测试用例但是我得到了运行时异常
@TestSubject
Session sessionn;
@Mock
Transaction transaction;
@MockSession
session;
@MockSQLQuery
mockQuery;
@Test
public void testSomeSuccessCheck() throws Exception {
HashMap map = new HashMap();
EasyMock.expect(HibernateSessionManager.getSessionFactory().openSession()).andReturn(sessionn);
EasyMock.expect(session.beginTransaction()).andReturn(transactionn);
EasyMock.expect(session.createSQLQuery(EasyMock.anyString()).addEntity(VehicleDetails.class)).andReturn(query);
EasyMock.expect((SomeObject) query.uniqueResult()).andReturn(someObj);
SomeObject respObj = vehDao.someMethod(map, errs);
assertNotNull(respObj);
}
我得到的完整错误跟踪:
java.lang.RuntimeException:在PowerMock测试侦听器org.powermock.api.extension.listener.AnnotationEnabler@5c87bfe2上调用beforeTestMethod方法失败。
Caused by: java.lang.NullPointerException: Have you forgotten to instantiate connection?
at org.easymock.internal.Injector.injectMocks(Injector.java:81)
at org.easymock.EasyMockSupport.injectMocks(EasyMockSupport.java:528)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.powermock.reflect.internal.WhiteboxImpl.performMethodInvocation(WhiteboxImpl.java:1846)
at org.powermock.reflect.internal.WhiteboxImpl.doInvokeMethod(WhiteboxImpl.java:810)
at org.powermock.reflect.internal.WhiteboxImpl.invokeMethod(WhiteboxImpl.java:790)
at org.powermock.reflect.Whitebox.invokeMethod(Whitebox.java:466)
at org.powermock.api.extension.listener.AnnotationEnabler.beforeTestMethod(AnnotationEnabler.java:73)
at org.powermock.tests.utils.impl.PowerMockTestNotifierImpl.notifyBeforeTestMethod(PowerMockTestNotifierImpl.java:82)
答案 0 :(得分:0)
首先,您需要模拟静态方法调用 HibernateSessionManager.getSessionFactory(),然后模拟 openSession ()方法调用。休息将保留为您添加的内容。
有关如何使用PowerMock的更多信息,请参阅此处:https://blog.codecentric.de/en/2016/03/junit-testing-using-mockito-powermock/
您也可以使用Mockito + Powermock来解决同样的问题。