【问题标题】:Spring boot unable to autowire class in tests after disable JPA禁用 JPA 后 Spring Boot 无法在测试中自动装配类
【发布时间】:2022-02-06 10:38:10
【问题描述】:

希望你们一切都好

我在测试我的 Spring Boot 应用程序时遇到了一些问题。我创建了一个简单的 API(目前只有一种方法,而且它正在工作)并创建了禁用 JPA 配置的域测试。当我在禁用 JPA 的情况下进行测试时,测试提供以下错误:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.mhrehbein.curriculum.register.infrastructure.mysql.ISpringDataAboutMeRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

当我启用 JPA 配置时,它工作正常,但是一旦它是单元测试,我想禁用它。您可以在以下 PR 中查看代码:https://github.com/retatu/curriculum/pull/6/files(对不起)

在代码中你可以看到所有测试都被破坏了,测试基本相同,示例在这里:https://github.com/retatu/curriculum/blob/dev/src/test/java/com/mhrehbein/curriculum/register/domain/entity/AboutMeTest.java

感谢任何帮助

【问题讨论】:

    标签: java spring-boot


    【解决方案1】:

    在您的代码中,您声明了一个扩展 PagingAndSortingRepository 的接口:

    public interface ISpringDataAboutMeRepository extends PagingAndSortingRepository<AboutMe, UUID> {
    }
    

    也就是说spring boot必须为你自动配置这个repository bean,即会配置一个SimpleJpaRepository的代理bean。

    但是由于您在application-test.properties 中禁用了DataSourceAutoConfiguration,因此没有配置DataSource bean,因此未激活自动JpaRepositoriesAutoConfiguration 并且用户定义的JPA 存储库(在您的情况下为ISpringDataAboutMeRepository)是未注册,导致NoSuchBeanDefinitionException。有关它的更多信息here

    此外,如果您禁用 HibernateJpaAutoConfiguration,则未配置 EntityManagerFactory bean,这是创建 ISpringDataAboutMeRepository bean 所必需的。

    因此,如果要运行 @SpringBootTest,则需要从 application-test.properties 中删除 spring.autoconfigure.exclude 属性并配置用于测试的数据库,例如内存中的 H2 数据库:

    添加到您的build.gradle

    testImplementation group: 'com.h2database', name: 'h2', version: '1.4.200'
    

    你的application-test.properties

    spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
    spring.datasource.username=sa
    spring.datasource.password=sa
    

    否则,您可以在测试类上使用 @MockBean 注释来模拟您的 ISpringDataAboutMeRepository 所以:

    @SpringBootTest
    @ExtendWith(SpringExtension.class) // remove it since  @SpringBootTest already contains it
    @TestPropertySource(locations = "classpath:application-test.properties")
    @MockBean(ISpringDataAboutMeRepository.class)
    public class AboutMeTest {
          ...
    } 
    

    【讨论】:

      【解决方案2】:

      Spring 有它的 spring 应用程序上下文,它作为 bean 的容器工作。 BeanFactory 代表 spring 控制容器的反转。它所做的是将 bean 暴露给应用程序。当您的应用程序需要一个不可用的 bean 时,它会抛出 NoSuchBeanDefinitionException

      我认为您的问题和根本原因最好在以下问题中得到解答。希望它能给你五个问题的见解。

      What is a NoSuchBeanDefinitionException and how do I fix it?

      【讨论】:

        猜你喜欢
        • 2014-07-30
        • 2020-03-24
        • 2020-02-09
        • 2017-07-17
        • 2020-06-22
        • 2014-03-11
        • 2017-02-25
        • 2021-12-23
        • 1970-01-01
        相关资源
        最近更新 更多