Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EUnit fails to test private functions

I'm writing EUnit tests for Erlang code.

I have a source module:

-module(prob_list).
-export([intersection/2,union/2]).

probability([], _Item) -> false;
probability([{First,Probability}|Rest], Item) ->
    if
        First == Item -> Probability;
        true          -> probability(Rest, Item)
    end.
...
...
...

and a unit-test module:

-module(prob_list_tests).
-include_lib("eunit/include/eunit.hrl").

-define(TEST_LIST,[{3,0.2},{4,0.6},{5,1.0},{6,0.5}]).
-define(TEST_LIST1,[{2,0.9},{3,0.6},{6,0.1},{8,0.5}]).
-define(TEST_UNO_LIST,[{2,0.5}]).

probability_test() -> ?assertNot(prob_list:probability([],3)),
                      ?assertEqual(0.5,prob_list:probability(?TEST_UNO_LIST,2)),
                      ?assertNot(prob_list:probability(?TEST_UNO_LIST,3)),
                      ?assertEqual(0.2,prob_list:probability(?TEST_LIST,3)),
                      ?assertEqual(1.0,prob_list:probability(?TEST_LIST,5)),
                      ?assertNot(prob_list:probability(?TEST_LIST,7)).
...
...
...

When I run eunit:test(prob_list,[verbose]) it says:

 prob_list_tests: probability_test...*failed*
::undef

but when I export probability/2 in my prob_list module, everything is ok.

Is there any way to test private functions?

like image 820
Uko Avatar asked Nov 13 '11 00:11

Uko


2 Answers

The general approach that I use for this is to include all of the unit tests in the same file and the separate them out:

-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.

%% Functions
[...]


-ifdef(TEST).
%% Unit tests go here.
-endif.

This should allow you to test your private functions alongside your public functions.

like image 54
David H. Clements Avatar answered Sep 21 '22 18:09

David H. Clements


You can use the directive -compile(export_all) to conditionally export all functions only when compiling for testing:

%% Export all functions for unit tests
-ifdef(TEST).
-compile(export_all).
-endif.
like image 22
Phil Calvin Avatar answered Sep 17 '22 18:09

Phil Calvin