10

Let us say I have a module called example.erl

In this module I use the following construct for debugging:

%%% Switch debugging output on/off:
%-define(DBG(Str, Args), ok).
-define(DBG(Str, Args), io:format(Str, Args)).

It helps me to output various debugging info into the Erlang shell:

?DBG("Function fun1 starting... ~n", [])

But if I call example.erl from example_tests with example:test(), this output info does not appear.

How can I make it visible during a EUnit test?

UPD: I have found some related info, but I still do not know how to solve the issue.

skanatek
  • 5,133
  • 3
  • 47
  • 75

2 Answers2

22

As describe in the page you mention, you can use debugMsg or debugFmt.

?debugMsg("Function fun1 starting...")

or

?debugFmt("Function fun1 starting...", [])

Make sure you have include eunit's header file in your module file.

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

If you want to disable debug macros for example in staging, define NODEBUG in compiling modules.

shino
  • 839
  • 5
  • 9
  • ?debugFmt works fine! But how can I switch it on/off quickly? I used to use ?DBG defined in two lines (as in my question). I have tried to do the following: `-define(dbgFmt(Str,Args), ok).`, but the output is still there. – skanatek Feb 11 '12 at 13:56
  • 4
    define NODEBUG macro such as `-define(NODEBUG, true).`. Make sure you define it **BEFORE** including eunit.hrl, – shino Feb 13 '12 at 00:25
1

Ran into a similar problem. Found another way thanks to @rvirding. The solution is to write to the user output stream (as in io:format(user, "~w", [Term])).

This is documented in the section titled "EUnit captures standard output" of the eunit docs.

My "trace.hrl" file is shown below:

%% If compiled with {d, TEST, true}
%% This happens automatically during `rebar3 eunit`
-ifdef(TEST).
-define(TRACE(Template, Args), io:format(user, "TRACE ~p:~p ~p~n", [?MODULE, ?LINE, lists:flatten(Args)])).
-else.
-define(TRACE(_T, _A), void).
-endif.

A sample source file:

-module(foo).
-export([ api/1 ]).

-include("trace.hrl").

api(Arg) ->
    ?TRACE("Called with Arg ~p~n", [Arg]),
    ok.

I prefer this method to ?debugFmt, as the latter injects EUnit specific code into your source (rather than test) code.

Manoj Govindan
  • 72,339
  • 21
  • 134
  • 141