Can't inject test Config into Play! 2.6 application created by Guice

cnmuc :

In a JUnit test in a Play! 2.6.25 application executed in IntelliJ, I'm trying to inject a test config:Config into an app:Application created by Guice. But the app:Application does not contain the injected config. What am I doing wrong?

Config config = ConfigFactory.parseFile(new File("test.conf")).resolve();
// myapp.key resolved to "value"
String value = config.getString("myapp.key");
GuiceApplicationBuilder guiceApplicationBuilder = new GuiceApplicationBuilder();
guiceApplicationBuilder.withConfigLoader(environment -> ConfigFactory.load(config));
Application app = guiceApplicationBuilder.build();
// why myapp.key cannot be resolved? 
app.config().getString("myapp.key");

test.conf

myapp.key = value

Also tried (without success):

guiceApplicationBuilder.loadConfig(config);
guiceApplicationBuilder.configure(config);
cbley :

You are actually discarding the Application Builder which has your custom config loader since the builder is an immutable data structure. Do it like this:

GuiceApplicationBuilder guiceApplicationBuilder = new GuiceApplicationBuilder()
  .withConfigLoader(environment -> ConfigFactory.load(config));

or simply

GuiceApplicationBuilder guiceApplicationBuilder = new GuiceApplicationBuilder()
  .configure(config);

When looking at the methods' signature you notice they all return (a new!) GuiceApplicationBuilder.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=400630&siteId=1