Erlang (programming language)/Tutorials/eunit
Jump to navigation
Jump to search
Sample program that uses eunit to test a function.
-module(power). -export([pow/2, start/0]). -include_lib("../../lib/eunit/include/eunit.hrl"). % adjust your own path
pow(_,0) -> 1; pow(X,1) -> X; pow(X,N) when N>1, is_integer(N) -> X * pow(X,N-1).
start() -> io:format(" This is a demo for eunit, the unit testing module.\n"), io:format(" Now testing the fact() function with eunit\n"), io:format(" Running: eunit:test(fact)~n"), eunit:test(fact).
power_test_() -> [?_assert(pow(0,0) == 1), ?_assert(pow(1,1) == 1), ?_assert(pow(2,2) == 4), ?_assert(pow(3,3) == 27), ?_assert(pow(4,4) == 256), ?_assertException(error, function_clause, pow(-1,0.5)) ].
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Note: Default unit test functions are automatically exported by eunit % % To test function power() we compile and test. % % 2> c(power). % 3> eunit:test(pow). % All 6 tests successful. % But how does it work? % eunit:test(fact) uses fact:fact_test_() to produce % a list of 6 test functions(a test suite): % 7> fact:fact_test_(). % {15,#Fun<pow.1.106864721>}, % {16,#Fun<pow.2.81990874>}, % {17,#Fun<pow.3.122231603>}, % {18,#Fun<pow.4.90957845>}, % {19,#Fun<pow.5.90843223>}] % % eunit:test then runs the programs in the test suite % and reports the results. % % Note: The numbers [15,16,17,18,19] are % the line numbers of the source code that generated the % test functions. % % Assertions % % Six total tests are run. An assertion is a positive assertion % and expects the answer to be true. There are 5 positive assertions % and 1 negative assertion in the test suite. % % Negative assertions % % A negative assertion is where an error is expected. % If an error is generated, then the test succeeds. % Since this power function does not know how to do % negative bases, then it causes an error. Since an % error is expected, the test succeeds. % % assertException(error, function_clause, pow(-1,0.5)) % % is an example of a negative assertion. % An error generates an exception. An exception is % is a type of high level error message. % % See Exceptions % for more details. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Note: for the program to work you will need to install and perhaps compile the eunit module, and set up your path to include it.