Spring 测试要连接数据库

标签 spring spring-boot unit-testing jpa mockmvc

我正在尝试为我的应用程序编写一些测试并遇到以下问题:
我定义了一个带有以下内容的 application-test.yml:

server:
  port: 8085

spring:
    security:
        oauth2:
            resourceserver:
                jwt:
                    # change localhost:8081 with container name
                    issuer-uri: http://localhost:8081/auth/realms/drivingschool
                    jwk-set-uri: http://localhost:8081/auth/realms/drivingschool/protocol/openid-connect/certs

keycloak:
    realm: drivingschool
    auth-server-url: http://localhost:8081/auth
    ssl-required: external
    resource: client-interface
    use-resource-role-mappings: true
    credentials:
        secret: xxx
    bearer-only: true
我的测试类:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
public class StudentControllerTests {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private StudentService service;

    @MockBean
    private StudentRepository repository;

    @Test
    public void contextLoads(){}
//more tests
}
测试全部通过绿色但我可以看到日志中的绿色,我的应用程序尝试连接到我的(基本)application.yml 中配置的数据库。
ava.sql.SQLNonTransientConnectionException: Could not connect to address=(host=localhost)(port=9005)(type=master) : Socket fail to connect to host:localhost, port:9005. Verbindungsaufbau abgelehnt (Connection refused)
    at org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory.createException(ExceptionFactory.java:73) ~[mariadb-java-client-2.6.1.jar:na]
    at org.mariadb.jdbc.internal.util.exceptions.ExceptionFactory.create(ExceptionFactory.java:192) ~[mariadb-java-client-2.6.1.jar:na]
jpa:
      database-platform: org.hibernate.dialect.MariaDBDialect
      hibernate:
        use-new-id-generator-mappings: false
        ddl-auto: create

    datasource:
      url: jdbc:mariadb://localhost:9005/waterloo
      username: waterloo
      password: xxx
      driver-class-name: org.mariadb.jdbc.Driver
创建 application-prod.yml 并将所有内容从 application.yml 移动到 application-prod.yml 时,它告诉我必须配置数据源 URL
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
我有以下问题:
  • application.yml 文件是否分层(*-test.yml 设置在 application.yml 之上)?
  • 当我没有在 application-test.yml 上设置数据源并在测试中模拟存储库时,为什么 Spring 会尝试建立到我的数据库的连接?
  • Spring在这部分尝试建立连接正常吗?
    3.1)如果不是:我如何防止它这样做?

  • 谢谢和亲切的问候!

    最佳答案

    Failed to determine a suitable driver class


    您需要将 mariadb 驱动程序依赖项添加到您的 gradle 或 maven 文件中。
    https://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client/2.6.2
    确保依赖范围适合测试
    如果您已经拥有但仍然无法正常工作,请尝试清理并重建您的项目。
    你的问题:

    Do the application.yml files get layered (*-test.yml settings on top of application.yml)?


    如果您添加 @ActiveProfiles("test")给你 TestClass Spring 将尝试找到一个 application-test.yml 并使用给定的属性覆盖 application.yml 属性

    Why does Spring try to build a connection to my database when I am not setting a datasource on my application-test.yml AND mocking the repository on the test?


    这就是 spring boot 的神奇之处——它对所有东西都有默认配置。您只需要设置 Datasource 属性,它就会自行创建 bean。

    Is it normal that Spring trys to establish a connection at this part? 3.1) If not: How to i prevent it from doing so?


    您正在使用 @SpringBootTest Annotation 启动整个 spring 上下文。
    因此它将启动所有存储库并尝试建立与数据库的连接。如果你不想让 spring 启动数据库层,你可以使用 @WebMvcTest
    例如:
    @RunWith(SpringRunner.class)
    @WebMvcTest
    @ActiveProfiles("test")
    public class StudentControllerTests {
    
        @Autowired
        private MockMvc mockMvc;
    
        @Test
        public void contextLoads(){}
    
        //more tests
    }
    
    看看这个:https://spring.io/guides/gs/testing-web/
    如果您需要启动整个 SpringContext,您还可以使用以下命令禁用 Spring Data AutoConfiguration:
    @SpringBootApplication(exclude = {
        DataSourceAutoConfiguration.class, 
        DataSourceTransactionManagerAutoConfiguration.class, 
        HibernateJpaAutoConfiguration.class
    })
    
    看看这个:https://www.baeldung.com/spring-data-disable-auto-config

    关于Spring 测试要连接数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63344810/

    相关文章:

    spring - Elasticsearch 返回空的 json 对象

    java - Spring Integration 一直消耗更多内存

    java - Spring Boot POST 请求特定负载不被接受

    spring - 创建自己的 xml 命名空间

    C# - 通过 IBM Websphere MQ 接收到的单元测试消息

    unit-testing - Hadoop 的 Maven 依赖项 : MiniDFSCluster & MiniMRCluster

    java - 从完全相同的 @Configuration 类习惯用法中注入(inject) @Beans

    java - 通过 XML 将属性注入(inject) Spring Rest Controller

    java - 转换 Hibernate 列表而不初始化它

    angularjs - 没有模板的测试指令属性