Instance-specific unittests

James Miller james at aatch.net
Mon Feb 13 15:40:13 PST 2012


On 14 February 2012 12:26, Jonathan M Davis <jmdavisProg at gmx.com> wrote:
> On Monday, February 13, 2012 15:12:15 H. S. Teoh wrote:
>> I discovered something really cool today, and I thought I'd share it
>> with my fellow learners:
>>
>> The unittest block is used for inserting unit tests that are executed at
>> runtime before main() is called. They are very useful for inserting
>> little tests after a piece of complex code, to make sure it actually
>> works as expected.
>>
>> What's cool is that if you have a unittest block inside a class or
>> struct with compile-time parameters:
> [snip]
>
> Terminology correction: It's once per _instantiation_, not per instance. An
> instance would be a constructed object.
>
> And yes, this can be useful. The problem that you get into is when you _don't_
> want your test to be in each instantiation of the template. In that case, you
> either end up having to use static if or move those unit tests out of the
> template.
>
> Regardless, the fact that unittest blocks get compiled into each individual
> template instantiation is something that anyone writing templated types should
> know.
>
> - Jonathan M Davis

Its pretty cool, I didn't think about it, but it makes sense, since
the compiler essentially makes a new version of the code for each
instantiation.

Also I imagine that common-to-all tests should probably be done inside
the templates (to ensure that all instantiations have the same
behaviour), then more general tests go outside the template, no reason
why you can't have two test blocks, especially if you lay the code out
so they are close together.


More information about the Digitalmars-d-learn mailing list