I have play web application with conf/application.conf (nothing unusual). Guice is used for dependency injection. How can property value be injected in class constructor? The code is below.
class MyController @Inject() (private val foo: Foo) extends Controller {
...
}
@ImplementedBy(classOf[FooImpl])
trait Foo {
def bar: String
}
class FooImpl extends Foo {
override val bar = current.configuration.getString("my.bar").get
...
}
In the current configuration FooImpl can't be tested without running application. I want to be able instantiate FooImpl in unit tests. The perfect solution [from my point of view] should look like that:
class FooImpl @Inject() (@Named("my.bar") override val bar: String) extends Foo {
...
}
Unfortunately, this code doesn't work, because Guice doesn't have 'my.bar' binding:
No implementation for java.lang.String annotated with @com.google.inject.name.Named(value=my.bar) was bound.
The only solution that I came up with is writing my own module, which iterates through configuration properties and binds them as named dependencies (a variation of the example from this doc). But I believe that a better approach exists.
FooImplshould declare a dependency toplay.api.Configurationits constructor. You can use something like Mockito to mock out theConfigurationobject in unit tests, without needing to construct a full config object. - Michael Zajac