gpt4 book ai didi

scala - 如何更改功能测试的 Guice 绑定(bind)?

转载 作者:行者123 更新时间:2023-11-28 19:47:38 24 4
gpt4 key购买 nike

我正在使用 Guice 作为 DI 提供程序开发一个 Play(v.2.4)应用程序。一切运行良好,但是我有一组使用 ScalaTestPlus 运行的功能测试,我想在测试运行时替换一些依赖项。这些测试是在检查我的 REST API 时通过扩展 OneServerPerSuite 类编写的。

有没有办法在测试期间有其他依赖?

编辑:示例代码:

示例 Controller :

class UserController @Inject()(userService: UserService) extends AbstractController { ... }

以及模块中的依赖定义:

bind(classOf[UserService]) to (classOf[ProdUserService])

我的测试是这样的:

class ApiTest extends PlaySpec with OneServerPerSuite {

"User API should" must {
"get User's data" in {
(...) //calling to an endpoint and verifying response
}
}
}

我想将 ProdUserService 替换为其他实现,但仅限于测试。

最佳答案

应该这样做:

import play.api.test._
import play.api.test.Helpers._
import play.api.inject.bind
import play.api.Application
import play.api.inject.guice.GuiceApplicationBuilder
import database.AccountDAO
import play.api.Configuration
import play.api.Mode

class ApiTest extends PlaySpec with OneServerPerSuite {

def app = new GuiceApplicationBuilder() // you create your app
.configure(
Configuration.from(
Map( // a custom configuration for your tests only
"slick.dbs.default.driver" -> "slick.driver.H2Driver$",
"slick.dbs.default.db.driver" -> "org.h2.Driver",
"slick.dbs.default.db.connectionPool" -> "disabled",
"slick.dbs.default.db.keepAliveConnection" -> "true",
"slick.dbs.default.db.url" -> "jdbc:h2:mem:test",
"slick.dbs.default.db.user" -> "sa",
"slick.dbs.default.db.password" -> "")))
.bindings(bind[UserService].to[UserServiceImpl]) // here you can define your bindings for an actual implementation (note the use of square brackets)
.in(Mode.Test)
.build()


"User API should" must {
"get User's data" in new WithApplication(app) {
// if you want to get the controller with everything injected
val app2controller = Application.instanceCache[controllers.UserController]
val userController = app2controller(app) // with this you get the controller with the service injected

(...) //calling to an endpoint and verifying response
}
}
}

关于scala - 如何更改功能测试的 Guice 绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32571148/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com