[Issue 4644] assertExceptionThrown to assert that a particular exception was thrown

d-bugmail at puremagic.com d-bugmail at puremagic.com
Tue Aug 17 08:04:32 PDT 2010


http://d.puremagic.com/issues/show_bug.cgi?id=4644



--- Comment #10 from Andrej Mitrovic <andrej.mitrovich at gmail.com> 2010-08-17 08:04:24 PDT ---
I have a revamped edition, this one is much nicer:

void assertExceptionThrown(alias E, alias func, T...)(lineFile info, T args)
    if(__traits(compiles, {try{}catch(E e){}}))
{
    try
        func(args);
    catch(E e)
        return;     // Expected exception was thrown

    throw new AssertError(format("assertExceptionThrown() failed: No %s was
thrown from %s()", E.stringof, __traits(identifier, func)), info._file,
info._line);
}

void assertExceptionThrown(string msg, alias E, alias func, T...)(lineFile
info, T args)
    if(__traits(compiles, {try{}catch(E e){}}))
{
    try
        func(args);
    catch(E e)
        return;     // Expected exception was thrown

    throw new AssertError(format("assertExceptionThrown() failed: No %s was
thrown from %s(): %s", E.stringof, __traits(identifier, func), msg),
info._file, info._line);
}

void assertExceptionNotThrown(alias E, alias func, T...)(lineFile info, T args)
    if(__traits(compiles, {try{}catch(E e){}}))
{
    try
        func(args);
    catch(E e)
        throw new AssertError(format("assertExceptionNotThrown() failed: %s was
thrown from %s()", E.stringof, __traits(identifier, func)), info._file,
info._line);
}

void assertExceptionNotThrown(string msg, alias E, alias func, T...)(lineFile
info, T args)
    if(__traits(compiles, {try{}catch(E e){}}))
{
    try
        func(args);
    catch(E e)
        throw new AssertError(format("assertExceptionNotThrown() failed: %s was
thrown from %s(): %s", E.stringof, __traits(identifier, func), msg),
info._file, info._line);
}


import std.stdio, std.stream, core.exception, std.string, std.typecons;

int myfunc(int i)
{
    return i;
}

struct lineFile
{
    string _file;
    uint _line;

    @property
    auto call(string file = __FILE__, uint line = __LINE__)
    {
        _file = file;
        _line = line;
        return this;
    }
}

void main()
{
    lineFile info;
    assertExceptionThrown!(core.exception.AssertError, myfunc)(info.call, 5);
}

Btw, I'm not sure I understand how you're supossed to call the template that
has "string msg" as a type parameter? Isn't that supossed to be next to the
function arguments, as in this:

void assertExceptionThrown(alias E, alias func, T...)(string msg, lineFile
info, T args)

instead of this:

void assertExceptionThrown(string msg, alias E, alias func, T...)(lineFile
info, T args)

?

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list