为什么 Eunit 坚持我的函数返回 {ok, value},而事实并非如此?



我正在做一些非常简单的事情:在不使用 BIF 的情况下反转 Erlang 中的列表。

这是我的尝试:

%% -----------------------------------------------------------------------------
%% Reverses the specified list.
%% reverse(List) where:
%%   * List:list() is the list to be reversed.
%% Returns: A new List with the order of its elements reversed.
%% -----------------------------------------------------------------------------
reverse(List) ->
reverse2(List, []).
%% -----------------------------------------------------------------------------
%% If there are no more elements to move, simply return the List
%% -----------------------------------------------------------------------------
reverse2([], List) -> 
List;
%% -----------------------------------------------------------------------------
%% Taking the head of the List and placing it as the head of our new List
%% This will result in the first element becoming the last, the 2nd becoming
%% the second last, etc etc.
%% We repeat this until we arrive at the base case above
%% -----------------------------------------------------------------------------
reverse2([H|T], List) ->
reverse2(T, [H|List]).

现在我相信这是正确的,并且每次都会在 shell 上用随机列表进行测试,给出正确的答案。这是我用来运行Eunit测试的代码:

%% -----------------------------------------------------------------------------
%% Tests the reverse list functionality.
%% -----------------------------------------------------------------------------
reverse_test_() -> [
{"Reverse empty list", ?_test(begin
% Reverse empty list.
?assertEqual([], util:reverse([]))
end)},
{"Reverse non-empty list", ?_test(begin
% Reverse non-empty list.
?assertEqual([5, 4, 3, 2, 1], util:reverse([1, 2, 3, 4, 5]))
end)}
].

这就是运行测试告诉我的,特别是:

error:{assertEqual,[{module,util_test},
{line,101},
{expression,"util : reverse ( [ ] )"},
{expected,[]},
{value,{ok,[]}}]}
output:<<"">>

这就是让我感到困惑的地方,我的函数reverse从不返回任何带有ok的内容,在终端中测试它不会输出任何带有ok的内容,但另一方面使用 EUnit 对其进行测试似乎返回{ok, value}

实际上代码看起来不错。也许您还有其他一些功能reverse/1util.erl尝试返回{ok, Value}。尝试在不显示指示的情况下更新测试util:

%% -----------------------------------------------------------------------------
%% Tests the reverse list functionality.
%% -----------------------------------------------------------------------------
reverse_test_() -> [
{"Reverse empty list", ?_test(begin
% Reverse empty list.
?assertEqual([], reverse([]))
end)},
{"Reverse non-empty list", ?_test(begin
% Reverse non-empty list.
?assertEqual([5, 4, 3, 2, 1], reverse([1, 2, 3, 4, 5]))
end)}
].

最新更新