【问题标题】:How to test Spring database down?如何测试Spring数据库?
【发布时间】:2020-10-13 18:01:03
【问题描述】:

我有这个使用 PostgreSQL 数据库的 SpringBoot 服务器应用程序,如果它启动并在它关闭时发送错误响应。因此,无论数据库连接如何,我的应用程序都在运行。

我非常想测试它(jUnit / mockmvc)。

我的问题很简单,但是网上没有找到答案:
SpringBoot中如何模拟数据库连接丢失?

如果有人愿意,我可以提供代码(项目在 https://github.com/k-wasilewski/workshop/

【问题讨论】:

标签: database spring-boot testing junit spring-data-jpa


【解决方案1】:

我之前通过创建一个创建 DataSource 并将其包装在 Java 代理中的 Spring Boot 测试配置类来完成此操作。代理只是将方法调用向下传递到底层数据源,直到设置了某个标志。一旦设置了标志,那么在代理上调用的任何方法都会抛出异常,而不会调用底层的 DataSource。从本质上讲,这让我可以通过翻转标志来“关闭”或“启动”数据库。

【讨论】:

    【解决方案2】:

    您可以基于DelegatingDataSource 实现自己的Datasource,然后让它抛出异常,而不是在您想要的时候进行委托。

    【讨论】:

    • 感谢您的回答,我确实设置了它,但是如何使测试用例使用 DelegatedDataSource 而不是原始目标?
    【解决方案3】:

    你有没有想过测试容器?你可以通过一个 Junit 测试来启动你的 docker 镜像,并让你的 spring boot 使用它作为你的数据库。 由于你使用了junit,你可以随意启动/停止这个容器。 这将生成一个测试,该测试会创建您正在寻找的条件并编写代码来说明数据库关闭时的预期。

    这里有一些开始的链接, Testcontainers 和 Junit4 与 Testcontainers 快速入门 - https://www.testcontainers.org/quickstart/junit_4_quickstart/

    Spring boot 文档 - 使用 Testcontainers 进行集成测试 https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-testcontainers

    springboot 应用的Testcontainer github 链接示例 https://github.com/testcontainers/testcontainers-java/tree/master/examples/spring-boot

    Testcontainer - 通用容器 javadoc。您可以找到启动/停止的方法 容器在这里。从你的 Junit 打电话。 https://javadoc.io/static/org.testcontainers/testcontainers/1.12.4/org/testcontainers/containers/GenericContainer.html

    【讨论】:

    • 已经加入了 :) 现在我正试图弄清楚如何逃避“端口 5432 已在使用中”
    • 如果端口被设置为你的springboot应用程序的属性,你可以让Testcontainers从一个随机端口启动,设置那个端口让springboot应用程序监听并启动它。
    • 如果您需要样品,这里有一个。使用 springboot 应用程序中的 mongodb。 testcontainer 建立一个 mongo 集群,获取 ip/port 等,并启动 springboot 应用程序。在测试期间永远不会以这种方式发生端口冲突。 gitlab.com/Oldtimes22/testcontainers/-/blob/master/mongodb/src/…
    • 非常感谢,但我得到 'Connection to localhost:5432 denied' 我无法摆脱...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 1970-01-01
    • 2017-05-04
    • 1970-01-01
    • 2012-04-24
    • 2020-12-25
    • 1970-01-01
    相关资源
    最近更新 更多