【问题标题】:Is there a way to test an IO output using Doctest in Elixir?有没有办法在 Elixir 中使用 Doctest 测试 IO 输出?
【发布时间】:2018-08-15 15:33:03
【问题描述】:

我完全可以为此编写一个捕获IO 的“正常”测试。

想知道是否可以使用Doctest

一个例子是:

defmodule CLI do

  @doc """
  Politely says Hello.

  ## Examples

      iex> CLI.main([])
      "Hello dear person." # this would be the expected IO output
  """
  def main(args) do
    IO.puts "Hello dear person."
  end
end

defmodule CLITest do
  use ExUnit.Case
  doctest CLI
end

【问题讨论】:

    标签: unit-testing io elixir doctest ex-unit


    【解决方案1】:

    您可以使用与普通测试相同的功能:ExUnit.CaptureIO.capture_io。但是,当您向函数添加更多功能时,这可能不是适合 doctest 的函数。

    defmodule CLI do
      @doc """
      Politely says Hello.
    
      ## Examples
    
          iex> import ExUnit.CaptureIO
          iex> capture_io(fn -> CLI.main([]) end)
          "Hello dear person.\\n"
      """
      def main(args) do
        IO.puts "Hello dear person."
      end
    end
    
    $ mix test
    .
    
    Finished in 0.03 seconds
    1 test, 0 failures
    

    【讨论】:

    • 是的,明白了。是的,对于这个具体的事情,我认为最好只进行“实际”测试。但这澄清了一堆。感谢@Dogbert。 =)。
    猜你喜欢
    • 1970-01-01
    • 2015-06-18
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 2017-02-07
    • 2020-08-31
    • 1970-01-01
    相关资源
    最近更新 更多