Simple bolt-on unittest improvement

Lutger lutger.blijdestijn at gmail.com
Sat Sep 12 03:52:24 PDT 2009


I'm rewriting my testing stuff at the moment, I hoped to use the runtime 
features to be able to user regular asserts too but that didn't work out.

Do you know you can get rid of the need to pass __FILE__ and __LINE__?

Define the functions this way:

void expectEquals(T)(T some_x, T some_y,
                     string file = __FILE__,
                     int line = __LINE__);

Default parameter initialization does the right thing here (in D2, dunno 
about D1).

I like the testing overhead to be as minimal as possible, for that purpose I 
have something hackish right now. Basically something like this:

void test(string testname)(void delegate () testClosure,
                           int LineNumber = __LINE__,
                           string FileName = __FILE__)
{
    writeln("running test ", name, " in ", FileName,"(", LineNumber,")");
    try
       testClosure();
    catch(Exception ex)
       // print test failure
    /* print test success. (actually first checks some flag set by expect*** 
functions to see if test passed)*/
}

And this:

void expectTrue(lazy bool exp, int LineNumber = __LINE__, 
                string FileName = __FILE__)
{
    if  (!exp())
        writeln("not true! ", FileName,"(", LineNumber,")");
}

usage:

unittest
{
    int a = 42;

    test!"foo" = {
        auto b = 42;
        expectEquals( a, b );
        expectTrue( a == a  );
        throw new Exception("fail!");
    };
}



More information about the Digitalmars-d mailing list