Unit tests in D

bearophile bearophileHUGS at lycos.com
Wed May 5 02:10:05 PDT 2010


>(it reports only the first failed assert for each unit test).<

I was wrong (or the behaviour on this is mutable).


Michel Fortin:


> Your 'throws' template seems good. Should create std.testing and 
> include it there.
> Also, perhaps it'd work to use a double-template for this:
> 	template throws(Exceptions...) {
> 		void throws(TCallable, string filename=__FILE__, int line=__LINE__)

Yes, thank you, with this suggestion of yours it works in D2 too:


class FooException : Exception { this(string msg) { super(msg); } }
class OtherException : Exception { this(string msg) { super(msg); } }

int sqr(int x) {
    if (x < 0)
        throw new FooException("");
    return x * 2;
}

template throws(Exceptions...) {
    bool throws(TCallable)(lazy TCallable callable) {
        try
            callable();
        catch (Exception e) {
            /*static*/ foreach (Exc; Exceptions)
                if (cast(Exc)e !is null)
                    return true;
            return false;
        }
        return !Exceptions.length;
    }
}

unittest {
    assert(throws!(OtherException)(sqr(-5)));
    assert(throws!(OtherException)( sqr(-5) ));
}

void main() {}


But I have to wrap it into another assert like that if I want it to behave as an assert inside the unittests. With a bit more compiler support it can be possible to write that in a library.

While the static throws can require more compiler support.

Bye,
bearophile


More information about the Digitalmars-d mailing list