gpt4 book ai didi

scala - 在 ScalaTest 中注入(inject) PlaySlick 数据库连接

转载 作者:行者123 更新时间:2023-12-04 04:09:57 29 4
gpt4 key购买 nike

我有以下使用 PlaySlick 连接到数据库的 DAO。该类有一个方法read我需要用 ScalaTest 进行测试。我的问题是我不知道如何模拟 DatabaseConfigProvider将其注入(inject) UsersDAO上课并测试read方法。这是要测试的类:

class UsersDAO @Inject()(@NamedDatabase("mydb") 
protected val dbConfigProvider: DatabaseConfigProvider)
extends with HasDatabaseConfigProvider[JdbcProfile] {

import driver.api._

val db1 = dbConfigProvider.get[JdbcProfile].db

def read (sk: Int) = {
val users = TableQuery[UserDB]
val action = users.filter(_.sk === sk).result
val future = db1.run(action.asTry)
future.map{
case Success(s) =>
if (s.length>0)
Some(s(0))
else
None
case Failure(e) => throw new Exception ("Failure: " + e.getMessage)
}
}

}

这是我编写测试的尝试:
class UserDAOTest extends PlaySpec with OneAppPerSuite  {

implicit override lazy val app = new GuiceApplicationBuilder().
configure(
Configuration.from(
Map(
"slick.dbs.mydb.driver" -> "slick.driver.MySQLDriver$",
"slick.dbs.mydb.db.driver" -> "com.mysql.jdbc.Driver",
"slick.dbs.mydb.db.url" -> "jdbc:mysql://localhost:3306/control",
"slick.dbs.mydb.db.user" -> "root",
"slick.dbs.mydb.db.password" -> "xxxxx"
)
)
).build

val dbConfigProvider = app.injector.instanceOf[DatabaseConfigProvider]

"Example " should {
"be valid" in {

val controller = new UsersDAO(dbConfigProvider)
val result = controller.read(1)
println(result)
}
}

当我运行测试时,它失败并显示以下错误消息:

com.google.inject.ConfigurationException: Guice configuration errors:

1) No implementation for play.api.db.slick.DatabaseConfigProvider was bound. while locating play.api.db.slick.DatabaseConfigProvider

最佳答案

恕我直言,最好不要干扰 Play 的注入(inject)东西,而只是使用它。这应该有效:

class UserDAOTest extends PlaySpec with OneAppPerSuite with ScalaFutures {

implicit override lazy val app = new GuiceApplicationBuilder().
configure(
"slick.dbs.mydb.driver" -> "slick.driver.MySQLDriver$",
"slick.dbs.mydb.db.driver" -> "com.mysql.jdbc.Driver",
"slick.dbs.mydb.db.url" -> "jdbc:mysql://localhost:3306/control",
"slick.dbs.mydb.db.user" -> "root",
"slick.dbs.mydb.db.password" -> "xxxxx").build

def userDAO(implicit app: Application): UserDAO = Application.instanceCache[UserDAO].apply(app)

"UserDAO" should {
"do whatever" in {
whenReady(userDAO.read(1)) { res =>
println(res)
}
}
}

}

我更新了我的 repo以防我错过了什么。

关于scala - 在 ScalaTest 中注入(inject) PlaySlick 数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41321559/

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