使用 state[:pid] 传递的消息失败,新生成的 pid 有效
Message passing with state[:pid] fails, freshly generated pid works
我的第二次测试失败了。
1) test it jumps when it can (RunnerTest)
test/runner_test.exs:15
No message matching %{y: 1} after 100ms.
The process mailbox is empty.
stacktrace:
test/runner_test.exs:18: (test)
defmodule RunnerTest do
use ExUnit.Case
doctest Runner
setup_all do
{:ok, pid: spawn(fn -> Runner.input() end)}
end
test "it increases its x position", state do
avatar = %{x: 0, y: 0}
send state[:pid], {:run, self, avatar}
assert_receive %{x: 1}
end
test "it jumps when it can", state do
avatar = %{x: 0, y: 0}
send state[:pid], {:jump, self, avatar}
assert_receive %{y: 1}
end
end
跑步者模块:
defmodule Runner do
def input do
receive do
{:run, sender, mover} -> send sender, run(mover)
{:jump, sender, mover} -> send sender, jump(mover)
end
end
defp run(mover) do
Map.merge(mover, %{x: mover.x + 1})
end
defp jump(mover) do
case {mover.y} do
{0} ->
Map.merge(mover, %{y: mover.y + 1})
_ ->
mover
end
end
end
此测试通过:
test "it jumps when it can", state do
avatar = %{x: 0, y: 0}
pid = spawn(fn -> Runner.input() end)
send pid, {:jump, self, avatar}
assert_receive %{y: 1}
end
为什么 1 个测试 (运行) 使用设置而不是另一个(跳转)?
Why is 1 test (run) working with setup but not the other (jump)?
这是因为您的进程只响应一条消息然后就死掉了,而您使用的是 setup_all
而不是 setup
,这意味着该进程只启动一次,在第一次测试之前运行,并且相同的 pid
传递给所有测试。
如果您想为每个测试生成一个新进程,您可以将 setup_all
更改为 setup
,或者让您的进程响应多于 1 条消息(使用自递归可能无限)。
我的第二次测试失败了。
1) test it jumps when it can (RunnerTest)
test/runner_test.exs:15
No message matching %{y: 1} after 100ms.
The process mailbox is empty.
stacktrace:
test/runner_test.exs:18: (test)
defmodule RunnerTest do
use ExUnit.Case
doctest Runner
setup_all do
{:ok, pid: spawn(fn -> Runner.input() end)}
end
test "it increases its x position", state do
avatar = %{x: 0, y: 0}
send state[:pid], {:run, self, avatar}
assert_receive %{x: 1}
end
test "it jumps when it can", state do
avatar = %{x: 0, y: 0}
send state[:pid], {:jump, self, avatar}
assert_receive %{y: 1}
end
end
跑步者模块:
defmodule Runner do
def input do
receive do
{:run, sender, mover} -> send sender, run(mover)
{:jump, sender, mover} -> send sender, jump(mover)
end
end
defp run(mover) do
Map.merge(mover, %{x: mover.x + 1})
end
defp jump(mover) do
case {mover.y} do
{0} ->
Map.merge(mover, %{y: mover.y + 1})
_ ->
mover
end
end
end
此测试通过:
test "it jumps when it can", state do
avatar = %{x: 0, y: 0}
pid = spawn(fn -> Runner.input() end)
send pid, {:jump, self, avatar}
assert_receive %{y: 1}
end
为什么 1 个测试 (运行) 使用设置而不是另一个(跳转)?
Why is 1 test (run) working with setup but not the other (jump)?
这是因为您的进程只响应一条消息然后就死掉了,而您使用的是 setup_all
而不是 setup
,这意味着该进程只启动一次,在第一次测试之前运行,并且相同的 pid
传递给所有测试。
如果您想为每个测试生成一个新进程,您可以将 setup_all
更改为 setup
,或者让您的进程响应多于 1 条消息(使用自递归可能无限)。