我目前正在测试使用函数 create_zone 的 Controller ,该函数依赖于检索用户以将所述用户与区域相关联的函数,然后创建参与者条目,该条目只是两个条目的关联表。
def create_zone(attrs \\ %{}, user_id) do
user = Accounts.get_user!(user_id)
with{:ok, %Zone{} = zone} <- %Zone{}
|> Zone.changeset(attrs,user)
|> Repo.insert()
do
create_participant(zone,user)
end
end
我想使用 ExUnit 对其进行测试,但问题是测试框架试图在数据库中搜索不存在的记录。
** (Ecto.NoResultsError) expected at least one result but got none in query:
from u in Module.Accounts.User,
where: u.id == ^1
我怎么能为了测试目的而模拟或创建它?
最佳答案
不要 mock 它,用 ex_machina 创建它:https://github.com/thoughtbot/ex_machina
Elixir 中不鼓励模拟:http://blog.plataformatec.com.br/2015/10/mocks-and-explicit-contracts/ (你现在真的不需要阅读它,但如果你想模拟一些外部资源,请阅读它)。
关于testing - Phoenix 丹药 : mock internal functions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46411134/