SpringBootTest 正在连接数据库 [英] SpringBootTest is connecting to database

查看:70
本文介绍了SpringBootTest 正在连接数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个测试,用于测试 Spring 应用程序的各个部分.它使用 SpringRunner 和 annotaion @SpringBootTest 所以它正在启动一个完整的 spring 服务器.

I have a test that is testing parts of a spring application. It is using SpringRunner and the annotaion @SpringBootTest so it is starting a full spring server.

问题是测试正在由无权访问数据库的服务器执行,因此我收到很多连接超时,这会减慢测试速度.

Problem is that the test is being executed by a server that does not have access to the database, so I am getting a lot of connection timeouts that is slowing down the test.

连接问题本身并不是真正的问题,因为测试是在模拟对数据库的调用,因此它们不依赖于存在的连接.只是测试很慢(而且很难看).

The connection issues in itself isn't really a problem as the tests are mocking the calls to the database, and so they are not relying on the connection being there. It is just that the tests are slow(and ugly) with it.

所以测试看起来像这样:

So the tests looks kind of like this:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class DispatcherTest

它使用这个属性文件

spring.datasource.url:jdbc:oracle:thin:@100.32.13.32:1521:TEST
spring.datasource.username:sa
spring.datasource.password:password
spring.datasource.driver-class-name:oracle.jdbc.OracleDriver
spring.jpa.database-platform:org.hibernate.dialect.Oracle10gDialect

我认为问题在于有很多不同的 JPA 存储库正在像这样被扫描

I think that the issue is that there are a lot of different JPA repositories that are being scanned like this

@EnableJpaRepositories("package.*")

那么有没有什么奇特的方式告诉 spring 不要连接到数据库,或者我是否必须模拟每个 JPA 存储库类?

So is there any fancy way of telling spring not to connect to the database or do I have to mock every single JPA repository class?

推荐答案

您可以使用 spring 配置文件来拆分您的配置.像这样:

You can use spring profiles to split your configuration. Something like this:

在这种情况下,我有三个配置文件来拆分每个配置.您可以在 此处查看文档此处.

In this scenario, I have three profiles to split each configuration. You can see the docs here and here.

要使用一些配置文件启动应用程序,只需执行以下操作:

To start an application with some profiles, just do this:

java -Dspring.profiles.active=development -jar yourApplication.jar

在您的情况下,您可以使用配置文件测试连接嵌入式(例如 H2)或其他本地数据库以测试实现.

In your case, you can use a profile test to connect an embedded (such as H2) or another local database for testing impls.

(我的母语不是英语,可能包含语法错误)

(I'm not a native English speaker, may contain grammar errors)

这篇关于SpringBootTest 正在连接数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆