Instance-specific unittests

H. S. Teoh hsteoh at quickfur.ath.cx
Mon Feb 13 16:11:42 PST 2012


On Tue, Feb 14, 2012 at 12:40:13PM +1300, James Miller wrote:
[...]
> 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.

I usually like to put unittests close to the code they're testing, which
means right after a function for tests related to that function. Much of
my code consists of alternating function definition / unittest blocks.

Which is what led me to discover this neat feature: unittests don't get
access to non-static variables, and you have to create actual instances
of structs/classes before you can actually test them, so it's not
obvious that they will be run multiple times for each instantiation
(thanks, Jonathan!). So I was quite surprised when a failed test case
led me to insert some writeln()'s, which produced unexpectedly
duplicated output because it ran twice.

In retrospect, it makes a lot of sense, especially given that you can
refer to the struct/class without specifying the compile-time
parameters, so unittests can apply across all instantiations just by
writing something like this:

	struct S(A,B,C,...) {
		...
		unittest {
			S s;
			/* tests common to all S(...)'s. */
		}
	}

Whereas if you placed the unittest outside the struct{}, you'd have to
individually test each combination of compile-time parameters of S: a
pain for a small number of combinations, totally infeasible as the
number of combinations increase (imagine having to test all possible
instantiations of struct S(int,int)).

Having the compiler generate multiple versions of the unittest per
instantiation is a totally awesome way of making such a situation
tractable: only test those instantiations that the program actually
uses.


T

-- 
Answer: Because it breaks the logical sequence of discussion. / Question: Why is top posting bad?


More information about the Digitalmars-d-learn mailing list