Have two tables say Employees and Department
have a test fixture, sessionWrapper, which wraps each test. sessionWrapper is a simple fuunction which creates a new session and rolls back, in a finally block, after test completes running. again tests aren't meant to poluate database and best thing we decied is to rollback data. this is achieved by a simple test fixture, sessionWrapper which wraps each test as shown below. fixture provides session(that it created) to each test.
Now I have a test which inserts a Employee record into Employees table. Employees table has FK relatinship with department table. so I need to first insert Department record part of this test.
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)
}
}
Throws
(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".)
shouldn't departmentRow insert be seen by employee insert in a same transaction?
this is a fairly common scenario so how do you generally test such a simple FK relation use case?
来源:https://stackoverflow.com/questions/25810910/slick-withsession-inserts-into-multiple-tables-test