简体   繁体   中英

Play 2.5 + Slick + DI Issue

I have DAO defined as follows:

@Singleton
class MyDAO @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends HasDatabaseConfigProvider[JdbcProfile]  {

I have an integration test which references this DAO:

class SomeIntegrationTest {
  lazy val someVal = new MyDAO
}

How can I inject the DatabaseConfigProvider into the MyDAO in the SomeIntegrationTest? I cannot inject one in the constructor of the test because test classes do not take constructor parameters.

You can get your dependency injected by doing

val dbConfigProvider = app.injector.instanceOf[DatabaseConfigProvider]

where app is an instance of your FakeApplication . Without it, there is no way Play can inject your dependency for you. You can get an instance of FakeApplication by extending OneAppPerSuite , see the provided link for more details.

In general, there are three main ways you can gain access to some object(s) in your test:

  • manual creation of objects using the new keyword (not considered best practice)
  • injection via injector as shown here (either injecting objects directly or injecting a provider/factory which can get them for you)
  • in case of unit testing a class with some dependencies, having those dependencies mocked

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM