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
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值