Elixir测试:从用例执行到覆盖率分析
立即解锁
发布时间: 2025-09-08 02:10:34 阅读量: 689 订阅数: 43 AIGC 


掌握Elixir测试精髓
### Elixir 测试:从用例执行到覆盖率分析
#### 1. 测试用例执行
在测试中,以 `Test` 结尾且包含 `use ExUnit` 的模块被视为测试用例。测试用例本质上是设置回调和测试的集合。测试用例的执行方式有两种:并发执行或顺序执行。使用 `async: true` 选项的测试用例将并发执行,其余的则按定义顺序(默认随机)顺序执行。
测试用例的执行流程如下:
1. 执行所有 `setup_all` 回调。
2. 执行所有测试及其特定的设置和拆卸回调。
`setup_all` 回调按定义顺序在同一进程中执行。在运行任何测试之前,测试用例将生成一个进程,在该进程中运行所有 `setup_all` 回调,然后开始运行测试。
单个测试用例中的测试默认按随机顺序顺序执行。因为单测试通常足够快,并行执行的开销可能大于顺序执行的时间。
单个测试的执行步骤如下:
1. 按定义顺序运行所有设置回调。
2. 运行测试主体。
3. 按注册顺序运行所有 `on_exit` 回调。
以下是一个测试用例的示例代码:
```elixir
# We use an empty list of formatters so that ExUnit doesn't
# output anything on the standard output.
ExUnit.start(autorun: false, formatters: [])
defmodule TestCaseExampleTest do
use ExUnit.Case
setup_all do
IO.puts("setup_all #1 in process: #{inspect(self())}")
end
setup_all do
IO.puts("setup_all callback #2 in process: #{inspect(self())}")
end
setup do
IO.puts("setup callback #1 in process: #{inspect(self())}")
end
setup do
IO.puts("setup callback #2 in process: #{inspect(self())}")
end
test "#1" do
on_exit(fn ->
IO.puts(
"on_exit callback #1 (test #1) in process: #{inspect(self())}"
)
end)
on_exit(fn ->
IO.puts(
"on_exit callback #2 (test #1) in process: #{inspect(self())}"
)
end)
IO.puts("test #1 in process: #{inspect(self())}")
end
test "#2" do
IO.puts("test #2 in process: #{inspect(self())}")
end
end
result = ExUnit.run()
IO.puts("The return value of ExUnit.run/0 is:")
IO.inspect(result)
```
运行该代码的输出如下:
```
setup_all #1 in process: #PID<0.109.0>
setup_all callback #2 in process: #PID<0.109.0>
setup callback #1 in process: #PID<0.110.0>
setup callback #2 in process: #PID<0.110.0>
test #2 in process: #PID<0.110.0>
setup callback #1 in process: #PID<0.111.0>
setup callback #2 in process: #PID<0.111.0>
test #1 in process: #PID<0.111.0>
on_exit callback #2 (test #1) in process: #PID<0.112.0>
on_exit callback #1 (test #1) in process: #PID<0.112.0>
The return value of ExUnit.run/0 is:
%{excluded: 0, failures: 0, skipped: 0, total: 2}
```
#### 2. 测试覆盖率
测试覆盖率是衡量测试对代码影响的常用指标,它表示代码库中被测试执行的代码的相对比例。例如,60% 的测试覆盖率意味着每十行代码中有六行在测试套件中至少执行了一次,而另外四行根本没有执行。
Elixir 和 Erlang 提供了内置的测试覆盖率支持。Mix 和 ExUnit 提供了默认的内置测试覆盖率工具以及对外部工具的支持。
##### 2.1 内置测试覆盖率工具
ExUnit 提供了一个内置的测试覆盖率工具,可以在 Mix 项目中通过 `--cover` 标志使用。
以下是使用示例:
```bash
> mix test --cover
Cover compiling modules ...
...............
Finished in 1.8 seconds
15 tests, 0 failures
Randomized with seed 38410
```
0
0
复制全文
相关推荐










