玩:如何用DI替换`Play.current`?
Play: How to replace `Play.current` with DI?
在尝试编写测试时,我从 Play 收到此警告:
You do not have an implicit Application in scope. If you want to bring the current running Application into context, please use dependency injection.
我发现如果我添加这个导入,它神奇地 解决了范围内应用程序的问题:
import play.api.Play.current
但是它会警告您
method current in object Play is deprecated: This is a static reference to application, use DI instead
如何使用依赖注入获得相同的结果?这是我需要的地方:
class TestSpec extends PlaySpec with OneAppPerSuite { ... }
编辑:我确实找到了 this post,但我不明白答案如何为我提供获得 implicit Application
.
有人向我指出了 this example(来自 @insan-e),它展示了如何解决这个问题。您无法注入测试 class,但您 "only" 需要用此覆盖您的 PlaySpec
:
import javax.inject.{Inject, Singleton}
import org.scalatestplus.play.{OneAppPerSuite, PlaySpec}
import play.api.Application
import play.api.inject.guice.GuiceApplicationBuilder
// To avoid repeating the `instanceCache` line below for each DAO
@Singleton
class DaoContext @Inject()(
val testDAO: TestDAO
// Other DAOs here
)
abstract class BetterSpec extends PlaySpec with OneAppPerSuite {
implicit override lazy val app = new GuiceApplicationBuilder().configure(...).build
protected def daoContext(implicit app: Application): DaoContext = {
Application.instanceCache[DaoContext].apply(app)
}
}
和测试:
class TestSpec extends BetterSpec {
"Test DAO" should {
"work" in {
val dao = daoContext.testDAO
// test it, finally
}
}
}
我知道,"what the hell????"但它奏效了。
N.B。现在它可以作为
的副本关闭
在尝试编写测试时,我从 Play 收到此警告:
You do not have an implicit Application in scope. If you want to bring the current running Application into context, please use dependency injection.
我发现如果我添加这个导入,它神奇地 解决了范围内应用程序的问题:
import play.api.Play.current
但是它会警告您
method current in object Play is deprecated: This is a static reference to application, use DI instead
如何使用依赖注入获得相同的结果?这是我需要的地方:
class TestSpec extends PlaySpec with OneAppPerSuite { ... }
编辑:我确实找到了 this post,但我不明白答案如何为我提供获得 implicit Application
.
有人向我指出了 this example(来自 @insan-e),它展示了如何解决这个问题。您无法注入测试 class,但您 "only" 需要用此覆盖您的 PlaySpec
:
import javax.inject.{Inject, Singleton}
import org.scalatestplus.play.{OneAppPerSuite, PlaySpec}
import play.api.Application
import play.api.inject.guice.GuiceApplicationBuilder
// To avoid repeating the `instanceCache` line below for each DAO
@Singleton
class DaoContext @Inject()(
val testDAO: TestDAO
// Other DAOs here
)
abstract class BetterSpec extends PlaySpec with OneAppPerSuite {
implicit override lazy val app = new GuiceApplicationBuilder().configure(...).build
protected def daoContext(implicit app: Application): DaoContext = {
Application.instanceCache[DaoContext].apply(app)
}
}
和测试:
class TestSpec extends BetterSpec {
"Test DAO" should {
"work" in {
val dao = daoContext.testDAO
// test it, finally
}
}
}
我知道,"what the hell????"但它奏效了。
N.B。现在它可以作为