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

时间:2017-09-26 21:07:20

标签: java unit-testing dropwizard

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

public class MyConfiguration extends Configuration

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

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

谢谢。

1 个答案:

答案 0 :(得分:3)

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

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

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

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);

    // ...

}