Testing Spring HIbernate JPA service layer with Mockito issue

Mobile Technologies Mobile Computing 2 years ago

0 1 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating
_x000D_ _x000D_ I am facing issue when trying to Run Junit Test class for my service class using Mockito.The JPA query is not getting executed. My DAO and service classes work fine when i run my spring classes , i am facing issue only when running Mockito Junit class.Below is the code. MY service class import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @Service public class DataBatchProcessorSvc { @Autowired DatasBatcProcessorDao dao; @Autowired DataAuditDaoImpl auditDao; @Transactional public Map> fetchBatchData() { return dao.fetchBatchData(); } @Transactional(propagation=Propagation.REQUIRED) public void saveBatchData(List DataList) { dao.saveBatchData(DataList); auditDao.saveAuditData(DataList); } @Transactional public void processBatch(List DataList){ this.saveBatchData(DataList); auditDao.saveAuditData(DataList); } } My Dao class import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @Repository public class DatasBatcProcessorDao { @PersistenceContext(unitName = "PersistenceUnitA") EntityManager entityManager; public Map> fetchBatchData() { Query query = entityManager.createQuery("SELECT e FROM Data e"); Collection resultList = query.getResultList(); Map> DataDetails = new HashMap>(); Iterator itr = resultList.iterator(); while (itr.hasNext()) { Data Data = itr.next(); String organizationKey = Data.getOrganizationId(); if (DataDetails.containsKey(organizationKey)) { List DatasList = DataDetails.remove(organizationKey); DatasList.add(Data); DataDetails.put(organizationKey, DatasList); } else { List DatasList = new ArrayList(); DatasList.add(Data); DataDetails.put(organizationKey, DatasList); } } return DataDetails; } } My Mockit Test class import static junit.framework.Assert.assertEquals; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class TestDataBatchProcessSvc { @Autowired @InjectMocks DatasBatcProcessorDao processtDao; @Autowired @InjectMocks DataBatchProcessorSvc processSvc; @Before public void setUp() { MockitoAnnotations.initMocks(this); Map> organizationDatas = new HashMap>(); List dataList = new ArrayList(); Data Data = new Data(); Data.setDataantName("Vinay"); Data.setOrganizationId("Mindtree"); Data Data2 = new Data(); Data2.setDataantName("Vinay"); Data2.setOrganizationId("Mindtree"); dataList.add(Data); dataList.add(Data2); organizationDatas.put("Mindtree", dataList); Mockito.when(processtDao.fetchBatchData()).thenReturn(organizationDatas); } @After public void tearDown() { } @Test public void saveAllAudit() { Map> batchData = processSvc.fetchBatchData(); assertEquals(2, batchData.get("Mindtree")); } } MY JPA Class import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "Data_details") public class Data { @Id @Column(name = "ID", nullable = false) @GeneratedValue(strategy=GenerationType.AUTO) private int id; @Column(name = "Dataaint_name", nullable = true) private String DataantName; @Column(name="organization_name",nullable=true) private String organizationId; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getDataantName() { return DataantName; } public void setDataantName(String DataantName) { this.DataantName = DataantName; } public String getOrganizationId() { return organizationId; } public void setOrganizationId(String organizationId) { this.organizationId = organizationId; } } When i am trying to this code . I get that Below exception org.hibernate.hql.internal.ast.QuerySyntaxException: Data is not mapped [SELECT e FROM Data e] when executing Mockito.when(processtDao.fetchBatchData()).thenReturn(organizationDatas); and i also assume that Mockito create mock object , since i am mocking my DAO class the call to my dao should not actual hit DB, please let me know if I am wrong . Stack Trace: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: Data is not mapped [SELECT e FROM Data e] at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1364) at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1300) at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:294) 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.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:366) at com.sun.proxy.$Proxy21.createQuery(Unknown Source) 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.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:241) at com.sun.proxy.$Proxy21.createQuery(Unknown Source) at com.mockitotest.batch.dao.DatasBatcProcessorDao.fetchBatchData(DatasBatcProcessorDao.java:26) at com.mockitotest.batch.svc.DataBatchProcessorSvc.fetchBatchData(DataBatchProcessorSvc.java:23) at com.mockitotest.batch.svc.DataBatchProcessorSvc$$FastClassByCGLIB$$3780f97d.invoke() at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:698) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631) at com.mockitotest.batch.svc.DataBatchProcessorSvc$$EnhancerByCGLIB$$c9ee8225.fetchBatchData() at TestDataBatchProcessSvc.saveAllAudit(TestDataBatchProcessSvc.java:46) 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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192

Posted on 16 Aug 2022, this text provides information on Mobile Computing related to Mobile Technologies. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (1)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago
_x000D_ Finally I was able to resolve the issue . There were two problems with my code 1) Using @autwired : This will inject actual object and not Mock Object 2) When to use @InjectMock and @Mock you get beautiful description here My Dao was the object that should be mocked and my service class is the place were these mocks have to be injected hence i made changes Marked myDao with @Mock and service class with @InjectMock Below is the modified code import static junit.framework.Assert.assertEquals; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class TestDataBatchProcessSvc { @Mock DatasBatcProcessorDao processtDao; @InjectMocks DataBatchProcessorSvc processSvc; @Before public void setUp() { MockitoAnnotations.initMocks(this); Map> organizationDatas = new HashMap>(); List dataList = new ArrayList(); Data Data = new Data(); Data.setDataantName("Vinay"); Data.setOrganizationId("Mindtree"); Data Data2 = new Data(); Data2.setDataantName("Vinay"); Data2.setOrganizationId("Mindtree"); dataList.add(Data); dataList.add(Data2); organizationDatas.put("Mindtree", dataList); Mockito.when(processtDao.fetchBatchData()).thenReturn(organizationDatas); } @After public void tearDown() { } @Test public void saveAllAudit() { Map> batchData = processSvc.fetchBatchData(); assertEquals(2, batchData.get("Mindtree").size()); } }

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.

Important Mobile Technologies Links