gpt4 book ai didi

testing - Dropwizard 集成测试与 DB 模拟

转载 作者:行者123 更新时间:2023-11-28 20:02:12 25 4
gpt4 key购买 nike

首先:是的,我读过这个https://dropwizard.github.io/dropwizard/manual/testing.html

我想做一些集成测试,这就是我必须启动整个应用程序的原因。现在的问题是,我有一些与“外部世界”的接口(interface),例如 DB 或一个与一个远程应用程序对话的内部 Rest-Client。我想用 mockito 来 mock 他们。通常这没问题。

现在我的问题是:如何使用模拟数据库和模拟客户端启动整个应用程序?

目前的问题是,我通过 getDBClient() 从我的配置类中获得了这个数据库连接和客户端......我不愿意在我的配置中构建一些测试代码,因为它的生产代码。因此,如果我通过 DropwizardAppRule 启动整个应用程序,该应用程序会尝试连接到数据库,但在测试环境中,没有可用的数据库。

有没有一种简单的方法可以说:启动我的应用程序,但如果您调用数据库或客户端,则使用此 XY 模拟?

我尝试过的:一个新类“ExtendedService extends Service extends Application”和一个“ExtServiceConfiguration extends ServiceConfiguration”,但没有任何成功。但是如果我重写返回模拟的配置类中的某些方法,我会遇到麻烦。它并不适合所有人。

目前我阅读了 mockito spy 的文档,也许这会有所帮助,但我不确定如何在 DW 集成测试中使用它。我现在尝试模拟 2 个配置类方法以返回数据库和客户端模拟。也许有人可以帮助我,如何在下一个示例代码中模拟 TestConfiguration:

@ClassRule
public static final DropwizardAppRule<TestConfiguration> RULE =
new DropwizardAppRule<TestConfiguration>(MyApp.class, resourceFilePath("my-app-config.yaml"));

编辑: @ClassRule public static final DropwizardAppRule RULE = new DropwizardAppRule(.....)

在@BeforeClass 中,我执行以下操作:

ServiceConfiguration oldConfig = RULE.getConfiguration();
ServiceConfiguration spy = Mockito.spy(oldConfig);
//Then DB mocking
IDatabaseLayer dBMock = mock(IDatabaseLayer.class);
Mockito.when(dBMock.isConnected()).thenReturn(true);
... // other mocking functions for DB
//this is important, it say, that the mocked config class should use the mocked DB
Mockito.doReturn(dBMock).when(spy).getDataBaseLayer(); // my configuration class has this method, so mocking config class with last created dbMock
// do other mockings if needed

这就是我启动整个应用程序所做的一切。

最佳答案

如果你真的想运行集成测试,我建议使用内存或临时数据库,如 h2sqlite,如果可以的话,通过创建一个新的 yml 文件具有相关设置;并使用模拟的 http 服务,例如 Wiremock .

否则按照 th3morg 的建议坚持 ResourceTestRule

关于testing - Dropwizard 集成测试与 DB 模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28874112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com