Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

scala - Play Slick: How to inject DbConfigProvider in tests

I am using Play 2.5.10, Play-slick 2.0.2, and my activator-generated project comes with scalatest and code like this:

class TestSpec extends PlaySpec with OneAppPerSuite {...}

I managed to test routes/Actions; now I would test DAO methods on a lower level. I searched the web and SO for a solution, and could not find any that is still up-to-date. A DAO signature is like this:

class TestDAO @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends HasDatabaseConfigProvider[JdbcProfile]

so I need to pass it the dbConfigProvider thing. For some reason I can't inject the provider into the tests like we do in controllers (no error, tests just won't run):

class TestSpec @Inject()(dbConfigProvider: DatabaseConfigProvider) extends PlaySpec with OneAppPerSuite {...}

The Play-Slick docs say we can alternatively use a global lookup

val dbConfig = DatabaseConfigProvider.get[JdbcProfile](Play.current)

but it won't work directly because

There is no started application

and link to an example project doing that:

class TestDAOSpec extends Specification {
  "TestDAO" should {
    "work as expected" in new WithApplicationLoader {   // implicit 'app'
      val app2dao = Application.instanceCache[TestDAO].apply(app)

but I could never find the WithApplicationLoader. Instead, there seems to be a WithApplication:

class TestDAOSpec extends Specification {
  "TestDAO" should {
    "work as expected" in new WithApplication() {   // implicit 'app'
      val app2dao = Application.instanceCache[TestDAO].apply(app)

but then I get

Type mismatch: expected a play.api.Application, got: play.Application.

At this point I lost hope.

How can I test a DAO?

N.B. I don't need to switch databases for testing (I handle this via config), I just want to access the default database in tests.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use:

lazy val appBuilder: GuiceApplicationBuilder = new GuiceApplicationBuilder().in(Mode.Test) 
lazy val injector: Injector = appBuilder.injector()
lazy val dbConfProvider: DatabaseConfigProvider = injector.instanceOf[DatabaseConfigProvider]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...