当前位置: 首页 > 知识库问答 >
问题:

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

包子航
2023-03-14

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

MY服务类

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

    }


}

我的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创建了模拟对象,因为我正在模拟我的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个答案

云伯寅
2023-03-14

我终于解决了这个问题。

我的代码有两个问题

1) 使用@autwired:这将注入实际对象,而不是模拟对象2)何时使用@InjectMock和@Mock,这里有漂亮的描述

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

    }


}
单于正业
2023-03-14

如果我理解正确,DataBatcProcessorDao的实例应该是一个Mock对象。然而,您的实现创建了一个真实的对象。尝试更改此代码

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

到此代码:

@Mock
DatasBatcProcessorDao processtDao;

processtDao将成为模拟对象

 类似资料:
  • 问题内容: 我对Java单元测试非常陌生,听说Mockito框架对于测试非常有用。 我已经开发了一个REST Server(CRUD方法),现在我想对其进行测试,但是我不知道如何? 我什至不知道该测试程序应该如何开始。我的服务器应该在本地主机上运行,​​然后在该URL上进行调用(例如,本地主机:8888)? 这是我到目前为止尝试过的方法,但是我很确定这不是正确的方法。 这是方法的代码。 在此测试用

  • 我在测试我的Spring Cloud stream服务(写入Kafka流)时遇到问题。它基于以下baeldung介绍 这是服务代码(具体省略) 这是测试 非常直接,但是在执行测试时,我得到一个NullPointerException,因为轮询返回一个Null。 知道问题是什么吗? 谢谢

  • 我正在尝试构建一个使用gradle作为构建工具和openjdk-11的原型。这个原型将在springboot框架上构建一个rest-api。 我的模块与rest api调用配合良好,并返回了预期结果。然而,当我现在试图为RESTAPI编写测试时,测试失败了,因为Mockito返回了空对象。如果您能了解我应该如何为这个rest api编写测试或如何修复它,我将不胜感激。 我的控制器: 服务: 模型:

  • 我在单元测试下面的Spring MVC控制器方法: 上面的自定义注释()基本上是由以下方面建议的: 如果抛出了一个,则会启动以下控制器建议异常处理程序: 现在,以下是我如何尝试测试上述控制器方法: 测试系统地失败了,下面的堆栈跟踪: 我不确定我和莫奇托有什么问题... 注意,我确实在路径中指定了,这表明我的模拟应该在方面中返回true,并允许控制器方法继续。然而,事实并非如此。 谁能帮忙吗?

  • 正在使用Spring MVC创建Restful Web服务... 下面是我的pom.xml: WEB-INF/web.xml: web-inf/mvc-dispatcher-servlet.xml: src/main/resources/database_db.xml: @Repository public class UserDAO{ } SRC/Test/Java: 这就像在print()语句

  • 像组件一样,服务通常需要依赖,Angular通过服务类的构造函数注入。由于我们在Angular的引导过程之外初始化这些类,我们必须自己显式注入这些依赖。这是通过使用TestBed配置测试模块传回所需的依赖项(如HTTP模块)来实现的。