unittesting generic functions

Jacob Carlborg via Digitalmars-d digitalmars-d at puremagic.com
Thu Aug 14 23:28:32 PDT 2014


On 15/08/14 04:46, H. S. Teoh via Digitalmars-d wrote:

> I agree that's a cool thing to have, but that still doesn't address the
> core issue, that is, given a generic type T, of which you have no
> further information about how its concrete values might behave, how do
> you write a unittest that checks whether some generic computation
> involving T produces the correct result? Even if I hand you some random
> instance of T, let's call it x, and you're trying to unittest a function
> f, how does the unittest know what the *correct* value of f(x) ought to
> be?
>
> Let's use a concrete example. Suppose I'm implementing a shortestPath
> algorithm that takes an arbitrary graph type G:
>
> 	path!G shortestPath(G)(G graph)
> 		if (isGraph!G)
> 	{
> 		... // fancy algorithm here
> 		return path(result);
> 	}
>
> Now let's write a generic unittest:
>
> 	unittest
> 	{
> 		// Let's test shortestPath on some random instance of G:
> 		auto g = G.random; // suppose this exists
> 		auto p = shortestPath(g);
>
> 		// OK, now what? How do we know p is the shortest
> 		// path of the random graph instance g?
> 		assert(p == ... /* what goes here? */);
> 	}

I don't know if this is how Andrei is thinking but it might be useful:

1. Instantiate "shortestPath" with random values of random types and 
assert that the instantiation succeeds

2. Then call "shortestPath" with known values of various types to 
validate that the algorithm is correct

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list