testing - Dropwizard 集成测试与 DB 模拟

标签 testing junit mockito dropwizard

首先:是的,我读过这个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/

相关文章:

java - 使用 Mockito 不使用 Maven

java - 从最终类(实用程序类)模拟私有(private)静态方法

java - 我们如何创建一个算法来检查一个字符串是否是两个字符串合并的结果?

Django 测试如何断言重定向

java - 为 "Step"作用域 bean 编写 JUnit 测试 - 没有为作用域名称 "step"注册作用域(Spring Batch 3.0.10)

java - 如何将简单的消息插入到 JUnit 输出中?

android - Mockito 在调用 Mockit.verify() 时避免传递方法参数

ruby-on-rails - Rails rake 测试返回错误消息

Python unittest 动态加载测试数据

java - 使用 JUnit 运行大量集成测试的更好方法是什么?