Play Slick:如何在测试中注入 DbConfigProvider [英] Play Slick: How to inject DbConfigProvider in tests
问题描述
我使用的是 Play 2.5.10、Play-slick 2.0.2,我的激活器生成的项目带有 scalatest 和如下代码:
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 {...}
我设法测试了路由/操作;现在我将在较低级别测试 DAO 方法.我在网上和 SO 上搜索了解决方案,但找不到任何仍然是最新的.一个 DAO 签名是这样的:
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]
所以我需要将 dbConfigProvider
传递给它.出于某种原因,我无法像在控制器中那样将提供程序注入到测试中(没有错误,测试不会运行):
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 {...}
Play-Slick 文档说我们也可以使用全局查找
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
没有启动的应用程序
并链接到执行此操作的示例项目:
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)
但我永远找不到WithApplicationLoader
.相反,似乎有一个 WithApplication
:
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)
但后来我明白了
类型不匹配:需要 play.api.Application,得到:play.Application.
Type mismatch: expected a play.api.Application, got: play.Application.
此时我失去了希望.
如何测试 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.
推荐答案
您可以使用:
lazy val appBuilder: GuiceApplicationBuilder = new GuiceApplicationBuilder().in(Mode.Test)
lazy val injector: Injector = appBuilder.injector()
lazy val dbConfProvider: DatabaseConfigProvider = injector.instanceOf[DatabaseConfigProvider]
这篇关于Play Slick:如何在测试中注入 DbConfigProvider的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!