【问题标题】:How can I test a multiline output in Elixir?如何在 Elixir 中测试多行输出?
【发布时间】:2018-09-27 22:33:43
【问题描述】:

如何测试以下代码?

["one", "two", "three"]) |> Enum.each(&IO.puts(&1))
one
two
three
:ok

我的测试目前看起来像这样,但失败了,因为 IO.puts 返回 :ok 而不是字符串,并且可能不包括完整字符串中的换行符。

assert ["one", "two", "three"]) |> Enum.each(&IO.puts(&1)) == """
one
two
three
"""

也许IO.puts 是这个用例的错误函数。如果是这样,我可以使用什么替代方案?

提前致谢。

【问题讨论】:

    标签: elixir stdout ex-unit


    【解决方案1】:

    使用capture_io

    fun = fn -> ["one", "two", "three"] |> Enum.each(&IO.puts/1) end
    assert capture_io(fun) == "one\ntwo\nthree\n"
    

    【讨论】:

    • 感谢您的出色回答。有没有一种方法可以让 doctest 处理前导空格? “我的字符串”
    • 对不起,我查了一下,doctest 不(不再?)支持捕获 io。我编辑了我的答案,因为关于 doctest 的部分是错误的。
    猜你喜欢
    • 2017-05-12
    • 1970-01-01
    • 2019-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-18
    • 2022-07-16
    相关资源
    最近更新 更多