On 9/9/22 10:35 AM, Andrey Zherikov wrote:
I have bunch of `static assert(<condition>, <message>)` in my code and would like to validate that specific code triggers specific assert by checking what `<message>` is thrown.

Right now I do `static assert(!__traits(compiles, { <my code> }));` but since `<my code>` might not compile due to many different reasons, I might not be testing original `static assert` and might miss breaking change.

One way to do this is to extract `<condition>` and `<message>` into some function and test it outside of `static assert`:
```d
auto check()
{
     return tuple(false, // check result  ('false' is just for example)
                  "message");
}

void f()
{
     enum result = check();
     static assert(result.condition, result.message);
}

unittest
{
     enum result = check();
     static assert(result.condition);
     static assert(result.message == "message");
}
```
But I don't like this approach because unit test doesn't really test `f()` (it tests duplicated code) so it can't guarantee that `f()` works as expected.


Is there a way to validate static asserts in unit tests?

Even this doesn't validate that you get the right message for the expected failure.

You can just test the message generation (and use a function for that). That's easier than doing some weird tuple thing.

But validating that the correct message comes out of a failed compilation can only be done outside compilation.

-Steve

Reply via email to