java - 如何在我的 dropwizard 应用程序的单元测试中创建配置对象?

标签 java unit-testing dropwizard

我们的 dropwizard 应用程序中有一个配置类:

public class MyConfiguration extends Configuration

我需要通过读取 yaml 文件在我的单元测试中创建真正的配置对象。任何指示都会有用吗?

看起来当 dropwizard 应用程序启动时,应用程序将读取 yaml 配置文件并创建 MyConfiguration 但我想要一个真实的(不是模拟的)配置对象,同时运行一个简单的单元测试。

谢谢。

最佳答案

将以下内容添加到 pom 的构建部分,以将 YAML 配置文件作为测试资源包含在内:

<testResources>
    <testResource>
        <directory>${project.basedir}/src/test/resources</directory>
    </testResource>
    <testResource>        
        <directory>${project.basedir}</directory>
        <includes>
            <include>config.yml</include>
        </includes>
    </testResource>
</testResources>

然后在您的单元测试中创建一个配置对象,如下所示:

import javax.validation.Validator;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.dropwizard.jackson.Jackson;
import io.dropwizard.jersey.validation.Validators;
import io.dropwizard.configuration.YamlConfigurationFactory;

// ...

@Test
public void test() {
    final ObjectMapper objectMapper = Jackson.newObjectMapper();
    final Validator validator = Validators.newValidator();
    final YamlConfigurationFactory<MyConfiguration> factory = new YamlConfigurationFactory<>(MyConfiguration.class, validator, objectMapper, "dw");

    final File yaml = new File(Thread.currentThread().getContextClassLoader().getResource("config.yml").getPath());
    final MyConfiguration configuration = factory.build(yaml);

    // ...

}

关于java - 如何在我的 dropwizard 应用程序的单元测试中创建配置对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46435856/

相关文章:

java - 在 Android 的 Recycler View 中将 Arraylist 发送到 Adapter 时出错

angular - Jasmine单元测试中MockService的UseValue导致测试失败

c# - 检查单元测试中是否抛出参数

java - boxfuse 应用程序无法连接到 RDS 数据库

java - 从某些方法调用模拟时出现奇怪的模拟 InvalidUseOfMatchersException

java - 检查一个字段是否设置为其在 Java 中声明的默认值

java - Java 2D数组大小更改错误

c# - 使用 Rhino Mocks 从模拟/ stub 中引发事件

java - dropwizard:从非文件源读取配置

java - 使用JDBI枚举数据库表