9

I have a module in Erlang which has functions that are not exported by Erlang. How can I test / call these functions using common test framework?

legoscia
  • 39,593
  • 22
  • 116
  • 167
Smarth Behl
  • 103
  • 6

4 Answers4

15

It is impossible. You can use -ifdef(TEST). preprocessor condition to export those functions only when compiling for testing.

Depending on your tooling, you might need to explicitly provide that TEST macro while compiling the modules. You can do that by using {d,'TEST'} compiler option or -DTEST compilation flag.

Dmitry Belyaev
  • 2,573
  • 12
  • 17
  • I tried this -ifdef(TEST). -export([ generate_perm_list/2 ]). -endif. In my module but it seems that TEST macro is not defined in common test. Is there any other macros that is defined in Common Test? – Smarth Behl Mar 16 '13 at 06:57
  • You need to compile your modules for testing with TEST macro defined by yourself. You can do that by using `{d,'TEST'}` compiler option or -DTEST compilation flag. – Dmitry Belyaev Mar 16 '13 at 08:27
2

It's tricky with Common Test, but it's possible to use embedded EUnit test cases to test private functions in a module. You can then test the public interface using Common Test. Rebar will automagically discover embedded test cases when you run rebar test.

Here's an example:

-module(example).

-export([public/1]).

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

%% This function will be tested externally using Common Test
public(Foo) ->
    private(Foo + 42).

%% This function is not reachable to CT, so it will be tested using EUnit.
private(Bar) ->
    Bar * 2.

%%% Tests
-ifdef(TEST).

private_test() ->
    ?assertEqual(10, private(5)),
    ?assertEqual(0, private(0)).

-endif.

On a side note, you might find Meck to your liking if you need to mock away a module (or parts thereof) when testing with EUnit.

For a gentle introduction to EUnit, see the Learn You Some Erlang chapter.

Martin Törnwall
  • 9,299
  • 2
  • 28
  • 35
0

You could put the private functions in their own module, which exports all of them. The original module can import them and they'll stay private, and your test framework can call import the private module directly.

amindfv
  • 8,438
  • 5
  • 36
  • 58
0

Just in case someone comes across this as well. Including the eunit.hrl file defines TEST unless NOTEST is defined before the include. -include_lib("eunit.hrl"). ref: http://www.erlang.org/download/eunit.hrl