Slick withSession插入多个表测试

时间:2014-09-12 14:42:31

标签: postgresql scala slick

有两个表格EmployeesDepartment

有一个测试夹具sessionWrapper,它包装每个测试。 sessionWrapper是一个简单的函数,可以在测试完成运行后在session块中创建新的finally并回滚。再次测试并不意味着数据库,我们决定最好的事情就是回滚数据。这是通过一个简单的test夹具sessionWrapper实现的,它包装了每个测试,如下所示。 fixture为每个测试提供session(它创建)。

现在我有一个测试,它将Employee记录插入Employees表。 Employees表与department表具有FK关联。所以我需要先insert Department记录此测试的一部分。

sessionWrapper { implicit session =>
  session.withTransaction {
    val departmentRow = DepartmentRow(1, Option("Department1"))
    val deptId = department.insert(departmentRow)

    val employeeRow = EmployeeRow(-1, Option(deptId), "John", "Doe")

    employee.insert(employeeRow)
  }
}

抛出

(org.postgresql.util.PSQLException:ERROR: insert or update on table "employees" violates foreign key constraint "fk_employees_department"
 Detail: Key (dept_id)=(1) is not present in table "department".)

不应departmentRow插入employee插入同一交易中吗?

这是一个相当常见的场景,所以你如何测试这样一个简单的FK关系用例?

0 个答案:

没有答案
相关问题