我想通过以下方法测试返回值和 IO 输出:
defmodule Speaker do
def speak do
receive do
{ :say, msg } ->
IO.puts(msg)
speak
_other ->
speak # throw away the message
end
end
end
在ExUnit.CaptureIO
文档中,有一个执行此操作的示例测试,如下所示:
test "checking the return value and the IO output" do
fun = fn ->
assert Enum.each(["some", "example"], &(IO.puts &1)) == :ok
end
assert capture_io(fun) == "some\nexample\n"
end
鉴于此,我认为我可以编写以下执行类似操作但使用spawn
ed 进程的测试:
test ".speak with capture io" do
pid = Kernel.spawn(Speaker, :speak, [])
fun = fn ->
assert send(pid, { :say, "Hello" }) == { :say, "Hello" }
end
assert capture_io(fun) == "Hello\n"
end
但是,我收到以下错误消息,告诉我没有输出,即使我可以在终端上看到输出:
1) test .speak with capture io (SpeakerTest)
test/speaker_test.exs:25
Assertion with == failed
code: capture_io(fun) == "Hello\n"
lhs: ""
rhs: "Hello\n"
stacktrace:
test/speaker_test.exs:30: (test)
spawn
那么,在测试ed 进程或使用receive
宏的方法方面,我是否遗漏了一些东西?如何更改我的测试以使其通过?