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

Moh*_*ali 5 junit spring unit-testing spring-test junit4

我在测试类中注入实体管理器时遇到问题。我认为这是因为我无法在测试类中加载 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
Run Code Online (Sandbox Code Playgroud)

这是我的测试课

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

    }

}
Run Code Online (Sandbox Code Playgroud)

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

@Configuration
public class NoteDeFraisTestConfig {

    @Bean
    NoteDeFraisDAO noteDeFraisDAO()
    {
        return new NoteDeFraisDAO();
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试将 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()
    {

    }

}
Run Code Online (Sandbox Code Playgroud)

Sam*_*nen 1

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

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

此处介绍:Spring-context.xml 的位置