播放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)
但由于
没有启动的应用程序
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)
,但是我找不到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.
在这一点上,我失去了希望.
At this point I lost hope.
如何测试DAO?
我不需要切换数据库进行测试(我可以通过config处理),我只想访问测试中的默认数据库.
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]
这篇关于播放Slick:如何在测试中注入DbConfigProvider的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!