Scala Play + Slick:如何向Spec测试注入依赖项?

时间:2019-05-25 21:22:51

标签: scala playframework slick slick-3.0 play-framework-2.7

我正在使用Scala Play 2.7.x(该项目可用here Play-Silhouette-Seed),并且想测试我的dao。我首先整理了这个简单的代码,以检查2.7.x中测试游戏+滑行+滑鼠的“新模式”是什么:

package models.daos

import java.util.UUID
import org.specs2.mock._
import org.specs2.mutable._
import utils.AwaitUtil
import javax.inject.Inject
import models.generated.Tables.LoginInfoRow

class LoginInfoDaoSpec @Inject() (loginInfoDao: LoginInfoDao) extends Specification with Mockito with AwaitUtil {

  "Creating a new LoginInfo" should {
    "save it in the empty database" in {
      loginInfoDao.create(LoginInfoRow(0, UUID.randomUUID().toString, UUID.randomUUID().toString))
      loginInfoDao.findAll.size should beEqualTo(1)
    }
  }
}

不幸的是,没有将guice依赖项LoginInfoDao提供给我的测试,然后出现错误:

[play-silhouette-seed] $ testOnly models.daos.LoginInfoDaoSpec
[info] Done compiling.
[error] Can't find a suitable constructor with 0 or 1 parameter for class models.daos.LoginInfoDao
[info] ScalaTest
[info] Run completed in 1 second, 966 milliseconds.
[info] Total number of tests run: 0
[info] Suites: completed 0, aborted 0
[info] Tests: succeeded 0, failed 0, canceled 0, ignored 0, pending 0
[info] No tests were executed.
[error] Error: Total 1, Failed 0, Errors 1, Passed 0

如何获得为测试用例加载所需模块的指南?

模块定义为:

class SilhouetteModule extends AbstractModule with ScalaModule {
  override def configure() {
    // ...
    bind[LoginInfoDao].to[LoginInfoDaoImpl]
    // ...
  }
}

我有一个application.test.conf可用定义为:

include "application.conf"

slick.dbs {
  default {
    profile="slick.jdbc.MySQLProfile$"
    db.driver="com.mysql.cj.jdbc.Driver"
    db.url="jdbc:mysql://localhost:3306/mytestdb?useUnicode=true&searchpath=public&serverTimezone=CET"
    db.user="dev"
    db.password="12345"
  }
}

1 个答案:

答案 0 :(得分:2)

您应该使用另一个数据库进行测试,H2是常见选择。

class Module extends AbstractModule with ScalaModule {
...
}

使用该名称,您需要让游戏知道要加载的模块,如果将其称为模块,它会自动知道要加载的模块,并且应该可以正常工作(如果您在测试中只需要一个模块)

如果这样不起作用,请告诉我