【问题标题】:Inject @PersistenceContext in test unit for spring在春季的测试单元中注入@PersistenceContext
【发布时间】:2017-12-13 12:04:07
【问题描述】:

在我的测试类中注入 entityManager 时遇到问题。我认为这是因为我无法在我的测试类中加载我的 spring 上下文。

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()
    {

    }

}

这是测试的配置,我知道当我使用 new 时,不会在 dao 中定义entitiesManager 注入,但我不知道该怎么做。

@Configuration
public class NoteDeFraisTestConfig {

    @Bean
    NoteDeFraisDAO noteDeFraisDAO()
    {
        return new NoteDeFraisDAO();
    }
}

我试图将我的 ContextConfiguration 设置为我的 applicationContext 但它不起作用我认为这是因为目录 WEB-INF 不属于类路径。我该如何解决这个问题??

这是我项目的结构

谢谢。

更新

这是我最后的测试课

@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()
    {

    }

}

【问题讨论】:

    标签: spring unit-testing junit junit4 spring-test


    【解决方案1】:

    是的,问题是为您的测试加载的ApplicationContext 不包含LocalContainerEntityManagerFactoryBean。假设在 applicationContext.xml 中正确声明,下面的链接解决方案将有所帮助。

    我试图将我的 ContextConfiguration 设置为我的 applicationContext 但它不起作用我认为这是因为目录 WEB-INF 不属于类路径。我该如何解决这个问题??

    这里有介绍:Location of spring-context.xml

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-31
      • 1970-01-01
      • 2016-01-19
      • 1970-01-01
      • 2022-10-12
      • 2012-07-18
      相关资源
      最近更新 更多