【发布时间】:2018-07-29 04:11:35
【问题描述】:
我在 Elixir 中有一个函数,可以在列表中生成三个随机 RGB 元组。
defmodule Color do
@doc """
Create three random r,g,b colors as a list of three tuples
## Examples
iex> colors = Color.pick_color()
iex> colors
[{207, 127, 117}, {219, 121, 237}, {109, 101, 206}]
"""
def pick_color() do
color = Enum.map((0..2), fn(x)->
r = Enum.random(0..255)
g = Enum.random(0..255)
b = Enum.random(0..255)
{r, g, b}
end)
end
当我运行我的测试时,我的 doctests 失败了。生成的元组列表与我的 doctest 中定义的不同。如何为返回随机值的函数编写文档测试?
【问题讨论】:
-
你不能。您只能对纯函数进行 doctest。
-
@JustinWood 您可以通过设置种子值使
Enum.random具有确定性(请参阅我的答案)。 :) -
您也可以(至少现在)在 doctests 中使用模式匹配:
iex> [_a, _b, {_r, 121, _b}] = Color.pick_color(),只是不要在后面的行中放置预期的返回值。万一出现错误,测试输出也将得到完善。