Unttests for nested functions

Daniel Keep daniel.keep.lists at gmail.com
Mon May 29 22:28:31 PDT 2006


I suppose the problem is that the inner function is inseperable from the
outer function.  Since the inner function shares the outer function's
stack, you can't really call it without the outer function.

The problem here is that unittests are run on program *startup*.  That
means that in order those unittests inside a function, it would have
to... uh... I dunno; maybe "fake" the function's stack.  But then you
just end up with random garbage data in the inner function.

The one idea I *could* come up with was this: firstly, pull the inner
function out into a template.  Then, in your unittest, mix the template
into a dummy stub function whose only job is to call the inner function
and return it's result.  So your example:

# int foo(int i)
# {
#     int j=0;
#
#     int bar(int k)  //////////
#     {
#         j+=k;
#     }
#     /+	cant make unit test here
#     unittest
#     {
#         bar(0);
#     }
#     +/
#
#     while(i);
#         bar(i--);
#
#     return j;
# }

Would become something like:

# template barT()
# {
#     int bar(int k)
#     {
#         j += k;
#     }
# }
#
# int foo(int i)
# {
#     int j = 0;
#
#     mixin barT;
#
#     while(i)
#         bar(i--);
#
#     return j;
# }
#
# unittest
# {
#     int j; // Out here so we can look at it.
#
#     int barShim(int arg)
#     {
#         mixin barT;
#         return bar(arg);
#     }
#
#     // Write tests here
# }

Please note that I have *not* tested the above.  Should work... the only
possible problem would be if the template wants a proper reference to
'j' (in that case, just pass it in as an alias).

Hope this helps.

	-- Daniel

BCS wrote:
> that is what I was expecting. :P  Any thoughts on how to make it so you can?
> (ref. my second post)
> 
> In article <1o4n88vezpkym$.1cj5tqvwrl0up$.dlg at 40tude.net>, Derek Parnell says...
>> On Sun, 28 May 2006 02:46:24 +0000 (UTC), BCS wrote:
>>
>>> how do I unittest bar?
>> Currently one can't directly test it using unit tests, however on the
>> assumption that the outer function uses the inner function I guess you can
>> test it indirectly, plus you can also use inner asserts and DbC.
> [...]
> 
> 

-- 

v1sw5+8Yhw5ln4+5pr6OFma8u6+7Lw4Tm6+7l6+7D
a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP    http://hackerkey.com/



More information about the Digitalmars-d-learn mailing list