我在尝试使用Mockito为我的服务类运行Junit Test类时遇到问题。JPA查询没有执行。当我运行spring类时,我的DAO和服务类工作得很好,只有在运行Mockito Junit类时我才会遇到问题。下面是代码。
我的服务等级
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<String, List<Data>> fetchBatchData() {
return dao.fetchBatchData();
}
@Transactional(propagation=Propagation.REQUIRED)
public <T> void saveBatchData(List<T> DataList) {
dao.saveBatchData(DataList);
auditDao.saveAuditData(DataList);
}
@Transactional
public <T> void processBatch(List<T> DataList){
this.saveBatchData(DataList);
auditDao.saveAuditData(DataList);
}
}
我的刀类
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<String, List<Data>> fetchBatchData() {
Query query = entityManager.createQuery("SELECT e FROM Data e");
Collection<Data> resultList = query.getResultList();
Map<String, List<Data>> DataDetails = new HashMap<String, List<Data>>();
Iterator<Data> itr = resultList.iterator();
while (itr.hasNext()) {
Data Data = itr.next();
String organizationKey = Data.getOrganizationId();
if (DataDetails.containsKey(organizationKey)) {
List<Data> DatasList = DataDetails.remove(organizationKey);
DatasList.add(Data);
DataDetails.put(organizationKey, DatasList);
} else {
List<Data> DatasList = new ArrayList<Data>();
DatasList.add(Data);
DataDetails.put(organizationKey, DatasList);
}
}
return DataDetails;
}
}
我的模拟测试类
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<String, List<Data>> organizationDatas = new HashMap<String, List<Data>>();
List<Data> dataList = new ArrayList<Data>();
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<String, List<Data>> batchData = processSvc.fetchBatchData();
assertEquals(2, batchData.get("Mindtree"));
}
}
MY JPA级
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;
}
}
当我尝试这个代码。我得到了以下异常
org.hibernate.hql.internal.ast.QuerySyntaxException:数据未映射[SELECT e FROM Data e]
执行时
Mockito.when(processtDao.fetchBatchData()).thenReturn(organizationDatas);
我还假设Mockito创建了mock对象,因为我在嘲笑我的DAO类,所以对我的DAO的调用不应该真正命中DB,如果我错了,请告诉我。
堆栈跟踪:
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(<generated>)
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(<generated>)
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
如果我理解正确,DatasBatcProcessorDao
的实例应该是Mock对象。然而,您的实现创建了一个真实的对象。尝试更改此代码
@Autowired // Autowired to get mockito to inject into the spring-handled dao
@InjectMocks
DatasBatcProcessorDao processtDao;
到此代码:
@Mock
DatasBatcProcessorDao processtDao;
processtDao
将成为模拟对象
我终于解决了这个问题。
我的代码有两个问题
1) 使用@autwired:这将注入实际对象,而不是模拟对象2) 当使用@InjectMock和@Mock时,你会在这里得到美丽的描述
我的刀是应该被嘲笑的对象,我的服务类是必须注入这些嘲笑的地方,因此我做了一些更改,用@Mock标记了我的刀,用@InjectMock 标记了服务类
以下是修改后的代码
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<String, List<Data>> organizationDatas = new HashMap<String, List<Data>>();
List<Data> dataList = new ArrayList<Data>();
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<String, List<Data>> batchData = processSvc.fetchBatchData();
assertEquals(2, batchData.get("Mindtree").size());
}
}