www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to unittest nested functions

reply "Tobias Pankrath" <tobias pankrath.net> writes:
How can i write a unittest for bar?

--

int foo()
{
     int bar()
     {
         return 42;
     }

     unittest { // not allowed
         assert(bar() == 42);
     }

     return bar();
}

unittest { // bar not visible
     assert(bar() == 42);
}

void main() {}
May 09 2012
parent reply "Jonathan M Davis" <jmdavisProg gmx.com> writes:
On Wednesday, May 09, 2012 22:32:09 Tobias Pankrath wrote:
 How can i write a unittest for bar?
 
 --
 
 int foo()
 {
 int bar()
 {
 return 42;
 }
 
 unittest { // not allowed
 assert(bar() == 42);
 }
 
 return bar();
 }
 
 unittest { // bar not visible
 assert(bar() == 42);
 }
 
 void main() {}

You can't. Either just unit test the outer function or extract the nested function as a private one outside of the outer one. And if you can't do that because it's a delegate, then it wouldn't make sense to unit test it anyway, because it's state relies on the outer function. If the function is major enough that it needs unit testing, it should probably be external anyway, but I can see why it might be a bit annoying to have to extract a function just to unit test it. - Jonathan M Davis
May 09 2012
parent reply "Era Scarecrow" <rtcvb32 yahoo.com> writes:
On Wednesday, 9 May 2012 at 20:38:05 UTC, Jonathan M Davis wrote:
 You can't. Either just unit test the outer function or extract  
 the nested function as a private one outside of the outer one. 
 And if you  can't do that because it's a delegate, then it 
 wouldn't make sense to unit  test it anyway,

Maybe. But if it doesn't need to be a delegate, you could tag static on it and give it a second go since it's just another function at that point. Worse case is it doesn't work. An idea is coming to mind to change it all to a struct and build and test it, then remove the outer struct when your done, but that's a second level of work. Just gotta consider the inner function as just another part of the function itself.
May 09 2012
parent reply "Andrej Mitrovic" <andrej.mitrovich gmail.com> writes:
On Wednesday, 9 May 2012 at 21:37:13 UTC, Era Scarecrow wrote:
 An idea is coming to mind to change it all to a struct

You don't even need to convert it all to a struct. Since having function-nested unittests is just a parser issue, you can do this: ----- int foo() { static int bar() { return 42; } struct _ { unittest { assert(bar() == 42); } } return bar(); } ----- However 'bar' must be marked static in order for this to work.
Jul 04 2013
parent "bearophile" <bearophileHUGS lycos.com> writes:
Andrej Mitrovic:

 You don't even need to convert it all to a struct. Since having 
 function-nested unittests is just a parser issue, you can do 
 this:

That's nice. If it's just a parser issue, then the right thing seems to fix such issue. Bye, bearophile
Jul 04 2013