Reputation: 305
We have a configuration class in our dropwizard application:
public class MyConfiguration extends Configuration
I need to create the real configuration object in my unit test by reading the yaml file. Any pointers would be useful?
It looks like when the dropwizard app is started, the application will read the yaml configuration file and create MyConfiguration but I want a real (not mocked) configuration object while running a simple unit test.
Thank you.
Upvotes: 4
Views: 4084
Reputation: 845
Add the following to the build section of your pom to include the YAML configuration file as a test resource:
<testResources>
<testResource>
<directory>${project.basedir}/src/test/resources</directory>
</testResource>
<testResource>
<directory>${project.basedir}</directory>
<includes>
<include>config.yml</include>
</includes>
</testResource>
</testResources>
Then in your unit test create a Configuration object like so:
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);
// ...
}
Upvotes: 4