我想编写测试,其中设置和清理功能不会为每个测试执行一次,而是一次 - 在测试开始和测试结束时。
所以我尝试了这种方式:
generator_test_() ->
{setup, fun setup/0, fun cleanup/1,
{inorder,
[
some_test1()
%...
]
}
}.
some_test1/0
在哪里
some_test1() ->
begin
Value1 = something1(),
Value2 = something2(),
[?_assertEqual(Value1, Value2)]
end.
安装程序不会以这种方式执行。
但是这样:
some_test1() ->
?_test(begin
Value1 = something1(),
Value2 = something2(),
[?_assertEqual(Value1, Value2)]
end).
或者
some_test1() ->
[?_assertEqual(something1(), something2())].
都很好。
我不明白它为什么起作用,我的问题是我不能在 ?_test(....) 中编写多个断言。
some_test1() ->
?_test(begin
Value1 = something1(),
Value2 = something2(),
[?_assertEqual(Value1, Value2),
?_assertEqual(Value1, Value2)]
end).
通过运行,eunit:test(my_module, [verbose]).
我看到只有 1 个测试通过了。
更新
示例 1
一个小例子:
-module(example).
-include_lib("eunit/include/eunit.hrl").
generator_test_() ->
{setup, fun setup/0, fun cleanup/1,
{inorder,
fun() -> some_test1() end
}
}.
some_test1() ->
begin
X = 3,
Y = 4,
%%% This is a test set/deep list as it
%%% contains two tests.
[?_assertEqual(X, Y),
?_assertEqual(ok, ok)]
end.
setup() ->
erlang:display("---SETUP CALLED---"),
"setup".
cleanup(_) ->
ok.
运行 eunit:
eunit:test(example, [verbose]).
======================== EUnit ========================
"---SETUP CALLED---"
module 'example'
example: generator_test_...ok
[done in 0.004 s]
=======================================================
Test passed.
ok
一个小修改:
some_test1() ->
begin
X = 3,
Y = 4,
%%% This is a test set/deep list as it
%%% containst two tests.
[?_assertEqual(X, Y),
?_assertEqual(it_doesnt_work, ok)]
end.
并且测试仍然通过。
示例 2
然而
some_test1() ->
begin
X = 3,
Y = 4,
%%% These are just two simple tests
?assertEqual(X, Y),
?assertEqual(it_doesnt_work, ok)
end.
失败
eunit:test(example, [verbose]).
======================== EUnit ========================
"---SETUP CALLED---"
module 'example'
example: generator_test_...*failed*
in function example:'-some_test1/0-fun-0-'/1 (example.erl, line 17)
in call from example:some_test1/0 (example.erl, line 17)
**error:{assertEqual_failed,[{module,example},
{line,17},
{expression,"Y"},
{expected,3},
{value,4}]}
[done in 0.003 s]
=======================================================
Failed: 1. Skipped: 0. Passed: 0.
error
但
示例 3
generator_test_() ->
{setup, fun setup/0, fun cleanup/1,
{inorder,
some_test1()
}
}.
some_test1() ->
[?_assertEqual(3, 3),
?_assertEqual(ok, ok)].
eunit:test(example, [verbose]).
======================== EUnit ========================
"---SETUP CALLED---"
module 'example'
example:13: some_test1...ok
example:14: some_test1...ok
[done in 0.005 s]
=======================================================
All 2 tests passed.
ok
现在我看到有 2(!) 个测试。
我可以忘记块语句并编写没有变量的测试,但我认为这可能很难阅读,它应该与块一起使用。