Spring 测试想要连接到数据库
Spring Test Wants To Connect to Database
我正在尝试为我的应用程序编写一些测试并遇到以下问题:
我定义了一个应用程序-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
我的测试class:
@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
在创建应用程序-prod.yml 并将所有内容从 application.yml 移动到应用程序-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 之上)?
- 为什么当我没有在我的应用程序上设置数据源时 Spring 尝试建立到我的数据库的连接-test.yml 并且在测试中模拟存储库?
- 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 引导的魔力 - 它具有所有内容的默认配置。您只需设置 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 注释启动整个 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 数据自动配置:
@SpringBootApplication(exclude = {
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
HibernateJpaAutoConfiguration.class
})
看看这个:https://www.baeldung.com/spring-data-disable-auto-config
缺少以下注释:
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class})
我正在尝试为我的应用程序编写一些测试并遇到以下问题: 我定义了一个应用程序-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
我的测试class:
@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
在创建应用程序-prod.yml 并将所有内容从 application.yml 移动到应用程序-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 之上)?
- 为什么当我没有在我的应用程序上设置数据源时 Spring 尝试建立到我的数据库的连接-test.yml 并且在测试中模拟存储库?
- 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 并使用给定的属性
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 引导的魔力 - 它具有所有内容的默认配置。您只需设置 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 注释启动整个 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 数据自动配置:
@SpringBootApplication(exclude = {
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
HibernateJpaAutoConfiguration.class
})
看看这个:https://www.baeldung.com/spring-data-disable-auto-config
缺少以下注释:
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class})