Elixir: Doctest, 在API文档中直接编写测试

快速上手

编写模块Doctest, 以及测试文档

defmodule Doctest do

  @doc """
  ## Examples

      iex> Doctest.add(1, 2)
      3
  """
  def add(a, b) do
    :not_implemented
  end
end

编写测试代码, 放在文件tests/doctest_test.exs文件中

defmodule DoctestTest do
  use ExUnit.Case, async: true
  doctest Doctest
end

执行测试

➜  mix test
lib/doctest.ex:9: warning: variable a is unused
lib/doctest.ex:9: warning: variable b is unused
Compiled lib/doctest.ex

  1) test doc at Doctest.add/2 (1) (DoctestTest)
     test/doctest_test.exs:3
     Doctest failed
     code: Doctest.add(1, 2) === 3
     lhs:  :not_implemented
     stacktrace:
       lib/doctest.ex:6: Doctest (module)

.

Finished in 0.1 seconds (0.1s on load, 0.00s on tests)
2 tests, 1 failure

Randomized with seed 301161

接下来我们事先Doctest模块中的add/2函数并在此运行测试

defmodule Doctest do

  @doc """
  ## Examples

      iex> Doctest.add(1, 2)
      3
  """
  def add(a, b) do
    a + b
  end
end

再次测试, 我们看到测试通过了

➜  mix test
Compiled lib/doctest.ex
..

Finished in 0.1 seconds (0.1s on load, 0.00s on tests)
2 tests, 0 failures

Randomized with seed 292239

注意要点

  • 文档测试以4个空格缩进, 并紧接着一个iex>

  • 如果测试代码有多行, 可以用...>换行, 类似于在IEx中输入多行代码, 只是没有(1)这种序号:

    iex(1)> defmodule A do
    ...(1)>   IO.puts "Create a module: A"
    ...(1)> end
    

你可能感兴趣的:(elixir)