[unittest] constness

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Sat Jan 17 19:23:16 PST 2015


On Saturday, January 17, 2015 00:38:08 Luc Bourhis via Digitalmars-d wrote:
> Testing constness implementation is easy:
>
> const Foo a;
> a.non_const_method(); // <<< compilation fails
>
> but how would I catch that in a unittest?

std.datetime has tests like this for that:

const cdate = Date(1999, 7, 6);
immutable idate = Date(1999, 7, 6);
static assert(!__traits(compiles, cdate.year = 1999));
static assert(!__traits(compiles, idate.year = 1999));

And you can make them one-liners by doing something like

static assert(!__traits(compiles,
    {const date = Date(1999, 7, 6); date.year = 1999; }));

though I think that it's probably better to not make them one-liners so that
the part that you want to test is isolated and doesn't test other stuff -
e.g. if the constructor call suddenly stopped compiling in that example for
some reason, the test would still pass, but it wouldn't be because of what
you were trying to test for. Other tests would probably catch it in the case
of the constructor, but still, minimizing what ends up in assertion reduces
the risk of accidentally have the test pass for the wrong reasons -
especially when the assertion is for something _not_ compiling.

- Jonathan M Davis



More information about the Digitalmars-d mailing list