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

JUnit的例外

邵刚洁
2023-03-14

我知道这个问题已经被问过很多次了,但是我已经坚持了几天,不知道为什么会这样。

这是我的JUnit测试套件,当我尝试@Autowire RequestService时会出现问题:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:**/*.xml"})
public class RequestServiceTest {
    @Autowired
    private RequestService requestService;

    @Test
    public void add() throws Exception {
        requestService.add(new Request(1, "hello"));
        requestService.add(new Request(2, "hi"));
        Request requestResponseFromDatabase = (Request) requestService.findById(1);
        assertEquals("hello", requestResponseFromDatabase.getRestRequestParameters());
    }
}

下面是我的模型、DAO和服务类的代码。

模型(为了简洁起见,省略构造函数和其他字段)

@Entity
public class Request implements Serializable {

    @Id
    private Integer restRequestId;

    private Timestamp restRequestTimestamp;

    private String restRequestParameters;
}

@Component
public class RequestDAO {

    @Autowired
    private RequestService requestService;

    @PersistenceContext
    private EntityManager entityManager;

    public void persist(Request request) {
        entityManager.persist(request);
    }

    public void update(Request request) {
        entityManager.getTransaction().begin();
        entityManager.merge(request);
        entityManager.getTransaction().commit();
    }

    public Object findById(Serializable id) {
        Request request = entityManager.find(Request.class, id);
        if (request == null) {
            throw new EntityNotFoundException("Cannot find Request for ID " + id);
        }
        return request;
    }

    public void delete(Request request) {
        entityManager.getTransaction().begin();
        entityManager.remove(request);
        entityManager.getTransaction().commit();
    }

    public void deleteById(Serializable id) {
        Request request = entityManager.find(Request.class, id);
        if (request == null) {
            throw new EntityNotFoundException("Cannot find Request for ID " + id);
        } else if (request != null) {
            entityManager.getTransaction().begin();
            entityManager.remove(request);
            entityManager.getTransaction().commit();
        }
    }

    public List<Request> findAll() {
        Query query = entityManager.createQuery("SELECT e from Request e");
        List<Request> requests = query.getResultList();
        return requests;
    }

    public void deleteAll() {
        List<Request> requests = findAll();
        for (Request request : requests) {
            delete(request);
        }
    }

}

服务

@Component
public class RequestService {

    @Autowired
    private RequestDAO requestDAO;

    @Transactional
    public void add(Request request) {
        requestDAO.persist(request);
    }

    @Transactional
    public void update(Request request) {
        requestDAO.update(request);
    }

    @Transactional
    public Object findById(Serializable id) {
        return requestDAO.findById(id);
    }

    @Transactional
    public void delete(Request request) {
        requestDAO.delete(request);
    }

    @Transactional
    public void deleteById(Request request) {
        requestDAO.delete(request);
    }

    @Transactional
    public void deleteAll() {
        requestDAO.deleteAll();
    }

    @Transactional
    public void addAll(Collection<Request> requestCollection) {
        for (Request request : requestCollection) {
            requestDAO.persist(request);
        }
    }

    @Transactional(readOnly = true)
    public List<Request> findAll() {
        return requestDAO.findAll();
    }
}

spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        ">


<!-- Scans the classpath for annotated components that will be auto-registered as Spring beans -->
    <context:component-scan base-package="com.company.mypackage"/>

    <!-- Activates scanning of @Autowired -->
    <context:annotation-config/>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
        <property name="url" value="jdbc:hsqldb:mem://requestDb"/>
        <property name="username" value="user"/>
        <property name="password" value="pass"/>
    </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
          p:packagesToScan="com.company.mypackage"
          p:dataSource-ref="dataSource">
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="generateDdl" value="true"/>
                <property name="showSql" value="true"/>
            </bean>
        </property>
    </bean>

    <bean id="transactionManger" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManger"/>


</beans>

完整堆栈跟踪:

May 23, 2016 1:57:38 PM org.springframework.test.context.support.DefaultTestContextBootstrapper getDefaultTestExecutionListenerClassNames
INFO: Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
May 23, 2016 1:57:38 PM org.springframework.test.context.support.DefaultTestContextBootstrapper instantiateListeners
INFO: Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
May 23, 2016 1:57:38 PM org.springframework.test.context.support.DefaultTestContextBootstrapper getTestExecutionListeners
INFO: Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@3498ed, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@1a407d53, org.springframework.test.context.support.DirtiesContextTestExecutionListener@3d8c7aca, org.springframework.test.context.transaction.TransactionalTestExecutionListener@5ebec15, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@21bcffb5]
May 23, 2016 1:57:38 PM org.springframework.context.support.GenericApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.GenericApplicationContext@548b7f67: startup date [Mon May 23 13:57:38 EDT 2016]; root of context hierarchy
May 23, 2016 1:57:38 PM org.springframework.test.context.TestContextManager prepareTestInstance
SEVERE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@1a407d53] to prepare test instance [com.company.mypackage.request.service.RequestServiceTest@57175e74]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.company.mypackage.request.service.RequestServiceTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.company.mypackage.request.service.RequestService com.company.mypackage.request.service.RequestServiceTest.requestService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.company.mypackage.request.service.RequestService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:385)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:249)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:119)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.company.mypackage.request.service.RequestService com.company.mypackage.request.service.RequestServiceTest.requestService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.company.mypackage.request.service.RequestService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    ... 30 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.company.mypackage.request.service.RequestService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545)
    ... 32 more


org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.company.mypackage.request.service.RequestServiceTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.company.mypackage.request.service.RequestService com.company.mypackage.request.service.RequestServiceTest.requestService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.company.mypackage.request.service.RequestService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:385)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:249)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:119)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.company.mypackage.request.service.RequestService com.company.mypackage.request.service.RequestServiceTest.requestService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.company.mypackage.request.service.RequestService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:573)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    ... 30 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.company.mypackage.request.service.RequestService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:545)
    ... 32 more


Process finished with exit code -1

其他细节

  • Spring版:4.2.5。发布
  • Hibernate版本:5.1.0。最终
  • 我的spring.xml位于src/main/Resources(是的,我知道这不是最佳实践,但想确保我的测试首先工作。我确实试图把它保存在我的src/test/Resources文件夹中,但一直遇到我的Application ationContext无法加载的问题)

资源如下:

  • @使用JUnit测试自动生成
  • @AUTOWIRED: BeanCreationExc0019
  • @自动生成JUnit失败

有没有办法解决这个问题?我在过去也问过类似的问题,并表示歉意——很难理解Spring及其所有文档。我想确保我完全理解这一点,以避免将来犯同样的错误。

编辑:这是我的文件夹结构:

使用@ContextConfiguration时的堆栈跟踪(位置={"classpath:spring.xml"})

May 23, 2016 3:20:39 PM org.springframework.test.context.support.DefaultTestContextBootstrapper instantiateListeners
INFO: Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
May 23, 2016 3:20:39 PM org.springframework.test.context.support.DefaultTestContextBootstrapper getTestExecutionListeners
INFO: Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@60f82f98, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@35f983a6, org.springframework.test.context.support.DirtiesContextTestExecutionListener@7f690630, org.springframework.test.context.transaction.TransactionalTestExecutionListener@edf4efb, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@2f7a2457]
May 23, 2016 3:20:39 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
May 23, 2016 3:20:39 PM org.springframework.context.support.GenericApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.GenericApplicationContext@174d20a: startup date [Mon May 23 15:20:39 EDT 2016]; root of context hierarchy
May 23, 2016 3:20:39 PM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: org.hsqldb.jdbcDriver
May 23, 2016 3:20:39 PM org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean createNativeEntityManagerFactory
INFO: Building JPA container EntityManagerFactory for persistence unit 'default'
May 23, 2016 3:20:39 PM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
May 23, 2016 3:20:39 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.1.0.Final}
May 23, 2016 3:20:39 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
May 23, 2016 3:20:39 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
May 23, 2016 3:20:39 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
May 23, 2016 3:20:40 PM org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator initiateService
WARN: HHH000342: Could not obtain connection to query metadata : User not found: USER
May 23, 2016 3:20:40 PM org.springframework.context.support.GenericApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [spring.xml]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
May 23, 2016 3:20:40 PM org.springframework.test.context.TestContextManager prepareTestInstance
SEVERE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@35f983a6] to prepare test instance [com.company.mypackage.request.service.RequestServiceTest@481ba2cf]
java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:249)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [spring.xml]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set


java.lang.IllegalStateException: Failed to load ApplicationContext

    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [spring.xml]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set



Process finished with exit code -1

共有2个答案

扶文光
2023-03-14

这里发生的问题是它无法加载您的springbean xml文件。能否将spring xml文件直接放在classpath的根级别。

赵飞雨
2023-03-14

错误消息非常清楚,您需要正确配置hibernate。

org.hibernate.HibernateException:未设置“hibernate.dialogue”时,对方言解析信息的访问不能为空

可能的原因可能是:

  1. 您的Hibernate设置不正确。
  2. 或者在测试期间没有DB运行
 类似资料:
  • 我正在为我的项目创建junit测试用例。我有下面的代码,我想在其中创建一个模拟, 我正在使用jUnit和mockito核心jar。我尝试了下面的代码, 使用上述代码,它在模拟loadProperties方法时抛出错误。如何模拟Spring静态类并返回我的模拟属性对象? 任何帮助都将不胜感激。

  • 我对junit mockito非常陌生,并尝试使用mockito编写junit测试用例。 这是我的方法,我必须为此编写一个jUnit。 ChefService和ChefApi传递的方法参数来自第三方api 这里是呼叫chefService。listCookbookVersions()将返回CookBookVersion类类型的迭代器,如

  • 问题内容: 是否使用对象的新(或不同)实例来运行JUnit测试用例中的每个测试方法?还是一个实例可用于所有测试? 运行此测试时,将创建多少个类实例? 如果可能的话,提供一个指向文档或源代码的链接,我可以在其中验证行为。 问题答案: 我在JUnit文档中找不到关于您问题的明确答案,但正如anjanb所写,其目的是每个测试都独立于其他测试,因此可以为要运行的每个测试创建一个新的TestCase实例。

  • 我有一个简单的测试用例: FileManager中的函数删除 /myDir下的所有文件,然后再次保留文件。 如上所述,我有一个。运行时,我可以按以下顺序查看所有打印: 但是,测试在失败。有两件事我不明白: > 我不明白,它在中失败了,为什么我仍然可以看到打印的,听起来就像是失败了,它没有停止运行,而是继续运行下一个测试?JUnit测试用例中的场景背后发生了什么?? 我不明白的另一件事是为什么tes

  • 我是新的火花与Java编程。我有一个从Oracle数据库读取数据的方法。现在我需要帮助编写测试用例使用JUnit框架为下面的代码。 数据集df=spark。read()。格式(“jdbc”)。jdbc(jdbcUrl、dbTable1、connectionProperties);

  • junit5-samples 仓库托管了很多基于JUnit Jupiter和JUnit Vintage的示例项目。可以在下面的项目中找到各自的build.gradle和pom.xml. 对于Gradle, check out junit5-gradle-consumer 项目. 对于Maven, check out junit5-maven-consumer 项目.