使用Mockito问题测试Spring HIbernate JPA服务层

时间:2015-12-02 12:58:49

标签: java spring hibernate jpa mockito

我在尝试使用Mockito为我的服务类运行Junit Test类时遇到问题.JPA查询未执行。当我运行我的Spring类时,我的DAO和服务类工作正常,我只在运行Mockito Junit类时遇到问题.Below是代码。

我的服务类

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);

    }

}

我的Dao课

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;
    }



}

我的Mockit测试课

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 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;
    }

}

当我尝试使用此代码时。我得到了以下异常

org.hibernate.hql.internal.ast.QuerySyntaxException:未映射数据[SELECT e FROM Data e]

执行时

Mockito.when(processtDao.fetchBatchData()).thenReturn(organizationDatas);

我还假设Mockito创建了模拟对象,因为我在模拟我的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

2 个答案:

答案 0 :(得分:0)

如果我理解正确,t+1的实例应该是Mock对象。但是,您的实现会创建一个真实对象 尝试更改此代码

DatasBatcProcessorDao

到此代码:

@Autowired // Autowired to get mockito to inject into the spring-handled dao
@InjectMocks
DatasBatcProcessorDao processtDao;

@Mock DatasBatcProcessorDao processtDao; 将成为模拟对象

答案 1 :(得分:0)

最后我能够解决这个问题。

我的代码存在两个问题

1)使用@autwired:这将注入实际对象而不是Mock对象 2)何时使用@InjectMock和@Mock,你会得到漂亮的描述here

我的Dao是应该被嘲笑的对象,我的服务类是这些模拟必须被注入的地方因此我做了更改用@Mock和服务类标记myDao @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());

    }


}