Catch block not hit in unittest

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Nov 24 07:51:06 PST 2016


On Thursday, November 24, 2016 15:41:12 Lucia Cojocaru via Digitalmars-d-
learn wrote:
> I was able to hack my way around it. In druntime there are other
> modules which need the exact same thing and have their own
> assertThrown template:
> https://github.com/dlang/druntime/search?utf8=%E2%9C%93&q=assertThrown
>
> So I did the same thing and defined assertThrown in my unittest.
> Now it works fine:
> unittest
> {
>      import core.exception : UnicodeException;
>
>      static void assertThrown(T : Throwable = Exception, E)(lazy E
> expr, string msg)
>      {
>          try
>              expr;
>          catch (T e) {
>              assert(e.msg == msg);
>              return;
>          }
>      }
>
>      static void f()
>      {
>          string ret;
>          int i = -1;
>          ret ~= i;
>      }
>
>      assertThrown!UnicodeException(f(), "Invalid UTF-8 sequence");
> }
>
> It is still unclear why this approach is necessary.
>
> Thanks,
> Lucia

I would advise against this, because it does not match what
std.exception.assertThrown does. It use the message you give as the message
in the AssertError that gets thrown on failure. It doesn't assert what the
message in the thrown exception is. It doesn't care. It just cares that the
right type of exception was thrown. If you want to check the message,
collectException is more appropriate (though you should check that it's
result is non-null, which my example didn't). Regardless, if you're talking
about essentially adding a Phobos function as a private helper in druntime,
it's a bad idea to make it operate differently from the one in Phobos. It
should either be the same, or it should be named differently.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list