scala – 如何更改功能测试的Guice绑定?
发布时间:2020-12-16 18:47:22 所属栏目:安全 来源:网络整理
导读:我正在使用Guice作为DI提供商的Play(v.4.4)应用程序.一切运行正常,但我有一组运行 ScalaTestPlus的功能测试,我想在测试运行时替换一些依赖项.测试是通过在检查我的REST API时扩展OneServerPerSuite类来编写的. 有没有办法在测试期间有其他依赖项? 编辑:示
我正在使用Guice作为DI提供商的Play(v.4.4)应用程序.一切运行正常,但我有一组运行
ScalaTestPlus的功能测试,我想在测试运行时替换一些依赖项.测试是通过在检查我的REST API时扩展OneServerPerSuite类来编写的.
有没有办法在测试期间有其他依赖项? 编辑:示例代码: 样品控制器: class UserController @Inject()(userService: UserService) extends AbstractController { ... } 模块中的dependecy定义: 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 } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |