【问题标题】:Slick and play controller testingSlick and play 控制器测试
【发布时间】:2014-09-14 15:03:35
【问题描述】:

有一个播放控制器方法

def insertDepartment = Action(parse.json) { request =>
  MyDataSourceProvider.db.withSession{ implicit session =>
    val departmentRow = DepartmentRow(1, Option("Department1"))
    departmentService.insert(departmentRow)
  }
}

注意MyDataSourceProvider.db 提供slick.driver.PostgresDriver.simple.Database 并创建withSession 提供implicit sessiondepartmentService.insert

当我测试departmentService 时,sessionthis post 中提到的文本夹具提供。 sessionWrapper 是一个简单的函数,它创建一个session,将session 提供给一个测试块,并在测试完成后回滚数据。

sessionWrapper { implicit session =>

    val departmentRow = DepartmentRow(1, Option("Department1"))
    departmentService.insert(departmentRow)
}

service 测试运行时不会污染数据库,这可以很好地工作并且符合预期。测试不应该在数据库中持久化任何东西,而是在成功执行后回滚。

现在在测试play controller 时需要一种使用sessionWrapper 的方法。能够以与service 测试类似的方式回滚控制器测试。

controller insertDepartment 中注明MyDataSourceProvider.db.withSession

sessionWrapper 包装controller test 没有意义,因为控制器def 不接受任何implicit session,而是使用MyDataSourceProvider.db.withSession 中的一个

处理此问题的最佳方法是什么?尝试创建一个trait 控制器,以便能够inject impl 为trait,因此对于测试和实际代码,mixin 可能会有所不同,但还没有找到一种方法来“通过”session 进行测试和 not 用于生产代码。有什么想法吗?

【问题讨论】:

    标签: scala playframework slick


    【解决方案1】:

    由于 Slick 被阻止,您不需要 Action.async。我想知道为什么会编译,因为我看不到那里的未来,但我对 Play 并不熟悉。

    您可以采取多种选择:

    1. 我的最爱:不使用事务回滚进行测试,而是使用测试数据库,您可以为每个测试重新创建该数据库。
    2. 拉出来

      val departmentRow = DepartmentRow(1, Option("Department1"))
          departmentService.insert(departmentRow)
      

      进入一个方法并且只测试那个方法,而不是控制器

    3. 在控制器中使用 sessionWrapper 并让它检查配置标志,告诉它是否处于测试模式并应该执行回滚,或者是否处于生产模式。

    【讨论】:

      猜你喜欢
      • 2016-04-26
      • 2016-03-03
      • 2018-06-14
      • 2016-02-21
      • 2016-11-14
      • 2016-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多