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
next sibling parent "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
prev sibling parent "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