代码之家  ›  专栏  ›  技术社区  ›  Mohamed Amine Ouali

在spring的测试单元中注入@PersistenceContext

  •  3
  • Mohamed Amine Ouali  · 技术社区  · 7 年前

    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'noteDeFraisDAO': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.persistence.EntityManagerFactory' available
    

    这是我的测试课

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = {NoteDeFraisTestConfig.class})
    @Transactional
    
    @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
    public class NoteDeFraisDAOIT
    {
        @Autowired
        private NoteDeFraisDAO noteDeFraisDAO;
    
        @Test
        public void myTest()
        {
    
        }
    
    }
    

    @Configuration
    public class NoteDeFraisTestConfig {
    
        @Bean
        NoteDeFraisDAO noteDeFraisDAO()
        {
            return new NoteDeFraisDAO();
        }
    }
    

    我曾尝试将ContextConfiguration设置为applicationContext,但没有成功。我认为这是因为目录WEB-INF不属于类路径。我怎样才能解决这个问题??

    这是我项目的结构 enter image description here

    谢谢

    这是我最后的测试课

    @WebAppConfiguration
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration({"file:web/WEB-INF/applicationContext.xml", "file:web/WEB-INF/db-config.xml","file:web/WEB-INF/dispatcher-servlet.xml","file:web/WEB-INF/security-config.xml"})
    @Transactional
    public class NoteDeFraisDAOIT
    {
        @Autowired
        private NoteDeFraisDAO noteDeFraisDAO;
    
        @Test
        public void myTest()
        {
    
        }
    
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Sam Brannen    7 年前

    是的,问题是 ApplicationContext 为测试加载的不包含 LocalContainerEntityManagerFactoryBean applicationContext.xml ,下面链接的解决方案将有所帮助。

    我曾尝试将ContextConfiguration设置为applicationContext,但没有成功。我认为这是因为目录WEB-INF不属于类路径。我怎样才能解决这个问题??

    这里包括: Location of spring-context.xml