I have a test class that looks something like this Behind the scenes, we're using Guice and DropwizardAwareModule to configure the binding and provide instantiated classes/beans.
class SomeTest {
companion object {
@RegisterExtension
@JvmField
val app = TestGuiceyAppExtension.forApp(MyServer::class.java)
.config(configFileName).hooks(GuiceyConfigurationHook {
builder(it)
}).create()
}
@Inject
@Named("something")
private lateinit var someClass: SomeClass
}
The SomeClass is defined in the following way:
class SomeClass(firstClass: FirstClass, secondClass: SecondClass) {
}
With no constructor injection.
In a separate DropwizardAwareModule, I define a Provides function that provides 2 possible instances of SomeClass. For example -
@Provides
@Named("something")
fun getSomeClass(firstClass: FirstClass, secondClass: SecondClass) {
return SomeClass(firstClass, secondClass)
}
The test class fails to inject SomeClass, claiming it doesn't have a no-args constructor, nor an @Inject annotated constructor, fair enough.
However, if I transform the field injection into a constructor injection, it works flawlessly.
That is - this configuration works well, and the SomeClass instance I provided in the module above, shows up alright.
class SomeTest @Inject constructor(@Named("something") someClass: SomeClass) {
}
Why is it so? is it because of some limitation in test classes? or is it something to do with @Provides generating an immutable instance, whereas field injection requires mutable objects?
Thanks!