让 rebar3 管项目:完整示例与补充知识
这里保留原课的完整资料,供你按需查阅;主看板只讲本课的核心问题。
创建 Erlang 应用,写第一个模块,再用 EUnit 保存例子。
创建 trail_counter 应用,让字符计数测试通过。
在项目模块中写第一个测试
先运行 rebar3 new app trail_counter,放入 src/trail_counter.erl,再执行 rebar3 eunit。
原课完整示例(按说明选择运行环境)
-module(trail_counter).
-export([text_length/1]).
-include_lib("eunit/include/eunit.hrl").
text_length(Text) ->
erlang:length(unicode:characters_to_list(Text)).
%% _test 结尾会被 EUnit 自动发现
unicode_length_test() ->
?assertEqual(2, text_length(<<"长安"/utf8>>)).测试通过时 EUnit 显示 1 tests passed。
完整示例的执行步骤
- 公开函数把 UTF-8 binary 转成码点 list 后计数。
- EUnit 头文件提供断言宏。
- rebar3 负责编译测试代码并运行用例。
原课补充说明
rebar3 是常用 Erlang 构建工具。它创建项目、编译代码、管理依赖并运行测试。
应用源码通常放 src/,配置写在 rebar.config。EUnit 适合短小单元测试。
测试函数名以 _test 结尾,或使用 EUnit 生成器。?assertEqual 写出期望和实际结果。
符号与术语对照
rebar3 new app name- 创建 OTP 应用骨架。
-include_lib("eunit/include/eunit.hrl").- 引入 EUnit 宏。
?assertEqual(Expected, Actual)- 比较期待值与实际值。
- rebar3
- Erlang/OTP 项目的构建与依赖工具。
- EUnit
- 随 Erlang/OTP 提供的轻量单元测试框架。
原课完整练习
再加一个空 binary 测试。
练习起点
empty_text_test() ->
?assertEqual(____, text_length(____)).期待 text_length(<<>>) 得到 0。
查看提示
两个空分别填 0 与 <<>>。
查看原课答案
答案参考
empty_text_test() ->
%% 空 binary 没有字符
?assertEqual(0, text_length(<<>>)).rebar3 是 Erlang 语言本身吗?
不是。它是项目构建工具;源码仍由 Erlang 编译器编译并在 BEAM 上运行。
原课要点
- rebar3 管理项目构建流程。
- EUnit 保存可重复检查的例子。
- 源码、配置与测试各有固定位置。