unittest Inheritance

BCS BCS at pathlink.com
Mon Sep 11 17:01:30 PDT 2006


Often when a class is used as a base class it is important that the 
derived class correctly implements a particular behavior. The place 
where this should be defined is in the parent class. To this effect, it 
should be able to test derived classes for correctness. Some sort of 
inherited unittest could make this work.

This could be done by allowing a unittest function to take a lazy 
parameter of the type of the class. Then when a class derives from the 
base class, it calls that unittest with "new DerivedClass(...)" as the 
argument. The unittest can then construct a number of objects and test 
them out.

Issues with this include how to make the parent class test the class 
with more than one set of arguments.

(P.S. This can wait for >1.0)

coded example:

class Foo
{
	/** test something that is a Foo to see if it acts like a Foo */
	unittest(lazy Foo FooGetter)
	{
		Foo f = FooGetter();
		Foo g = FooGetter();

		for(int i=-100; i<=100; i++)
		{
			f.fig = i;
			g.fig = 150-i;
			assert(i == f.fig);
			assert((150-i) == g.fig);
		}

		f.put(10,"hello!");
		g.put(22,"bob!");

		assert("hello" == f.get(10,"hello".length));
		assert("bob" == g.get(22,"bob".length));
	}

	int fig();
	void fig(int i);

	void put(int i, char[] data);
	char[] get(int i, int len);
}

class Bar : Foo
{
	char[][int] field;
	int i;

	int fig() {return i;}
	void fig(int j){i=j;}

	void put(int i, char[] data) {field[i] = data; }
	char[] get(int i, int len)
	{
		auto ret = i in field;
		if(ret is null) throw new Error("Bah!");

		for(int s = ret.length; s<i; ret ~=' ';
		return ret[0..i];
	}

}



More information about the Digitalmars-d mailing list