Erlang Testing (Non Exported / Private) function of module using common test
Asked Answered
J

4

10

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?

Jane answered 15/3, 2013 at 13:21 Comment(0)
N
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.

Noontime answered 15/3, 2013 at 13:53 Comment(2)
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?Jane
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.Noontime
S
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.

Stela answered 16/3, 2013 at 16:4 Comment(0)
C
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.

Consumptive answered 16/3, 2013 at 2:28 Comment(0)
K
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

Konopka answered 11/11, 2013 at 2:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.