Building a Generic Statistics Library, Part 2: Unit Tests

Posted by on in Blogs
Yesterday, I introduced a short series I'm writing on building a statistics library using Delphi 2009 generic methods, and discussed the signature of the Average function.  Since I have a signature, I have enough to start writing unit tests, even without an implementation. Not only does this allow me to check that my implementation works, it's also a convenient way to run routines in a library-in-progress, without building a "throwaway" user interface.

So I added a new test project to my project group, and then I added a new test case to the test project.  The test case wizard got confused by the class methods, so I just wrote the tests manually.  They're quite simple:

uses
TestFramework, Classes, Unit7, Generics.Collections, SysUtils;

type
TestTIntStatistics = class(TTestCase)
published
procedure TestAverage;
procedure TestStandardDeviation;
end;

implementation

procedure TestTIntStatistics.TestAverage;
var
ReturnValue: Integer;
AData: TList<integer>;
begin
AData := TList<integer>.Create;
try
AData.Add(2);
AData.Add(4);
AData.Add(6);

ReturnValue := TIntStatistics.Average(AData);

CheckEquals(4, ReturnValue);
finally
AData.Free;
end;
end;

procedure TestTIntStatistics.TestStandardDeviation;
var
ReturnValue: Integer;
AData: TList<integer>;
begin
AData := TList<integer>.Create;
try
AData.Add(2);
AData.Add(4);
AData.Add(6);

ReturnValue := TIntStatistics.StandardDeviation(AData);

CheckEquals(1, ReturnValue);
finally
AData.Free;
end;
end;


I have just created a small list with values for which it is easy to calculate the average and (integer) standard deviation in my head, and checked that the values returned by my functions correspond to the values I calculated myself. That's not a rigorous test, but it's enough to allow me to debug through my code and check for obvious failures.

Of course, I haven't actually implemented the functions yet, so the tests fail:

Generic Statistics Library unit test failure

With a functioning unit test, however, I can start implementing the library.  In the next post, I'll start to discuss some of the higher order functions the library will use internally.
Tags: Delphi


Comments

Check out more tips and tricks in this development video: