unittest questions

Simen kjaeraas simen.kjaras at gmail.com
Thu Aug 19 13:00:18 PDT 2010


Johannes Pfau <spam at example.com> wrote:

> Hi, I wrote some unittests using the built-in d unittest and a came
> across 2 problems:
>
> 1) I have some code that accepts both delegates and functions. How can a
> unittest explicitly check the function part? Whenever I add a function
> in an unittest block it becomes a delegate.
> ---------------------------------------------------
> void add(T)(T handler) if (is(T == void function())){}
> void add(T)(T handler) if (is(T == void delegate())){}
>
> unittest
> {
>     //always a delegate
>     void handler() {};
>     add(&handler);
> }
> ----------------------------------------------------

You can use version statements[1] to place the function outside the
unittest scope:

version( unittest ) {
     void handler() {}
}

unittest {
     add( &handler );
}

You could also use function literals[2]:

unittest {
     add( function void() {} );
}


> 2) I know Errors should not be caught. But when I expect a function to
> throw in debug mode, but not necessarily in release mode (assert), I
> have to check for both Errors and Exceptions --> Throwable. Is it OK to
> catch Throwables in this case?
> ----------------------------------------------------
> unittest
> {
>     void handler() {};
>     bool thrown = false;
>     try
>         add(&handler);
>     catch(Throwable)
>         thrown = true;
>
>     assert(thrown);
> }
> ----------------------------------------------------

Yes.


[1]: http://www.digitalmars.com/d/2.0/version.html#version
      http://www.digitalmars.com/d/2.0/version.html#PredefinedVersions
[2]: http://www.digitalmars.com/d/2.0/expression.html#FunctionLiteral
-- 
Simen


More information about the Digitalmars-d-learn mailing list