Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k 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 Reply

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...