I recommend you start with FPTest (a FPC specific fork of DUnit2) [
http://wiki.freepascal.org/FPTest]. It is much improved and easier to use that FPCUnit, plus it has backward compatibility with DUnit and FPCUnit too.
The concept of writing unit tests are pretty simple.
- You create a new unit which will contain some tests
- Add the TestFramework unit to the Interface section's uses clause
- Define a new test class which descends from TTestCase
- Define test procedures in the Published section of the above mentioned test class
- Implement the test procedures by using the CheckXXX() methods. eg: CheckTrue(), CheckEquals() etc. They normally have two or three parameters... An "expected" value, the "actual" value, and a "error message". My error messages are normally in the format of "Failed on 1", "Failed on 2" etc, so that if I see the error message in the results, I know exactly which test and which CheckXXX() call failed.
- Now you need to register that test class with the testing framework. This is normally done in the Initialization section of the unit. eg: TestFramework.RegisterTest(TMyTest.Suite);
- Test projects can be Console or GUI based, and normally consist of many test units, all defined as above. The project then simply calls RunRegisteredTests, and it will output your test results.
That's it!

Putting it all together, here is our Console test program unit.
program project1;
{$mode objfpc}{$H+}
{$IFDEF WINDOWS}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
Classes
,sample_tests // is the unit that contains our tests
,TextTestRunner // Enables the Console test runner
// ,GuiTestRunner // Enables the GUI test runner
;
begin
RunRegisteredTests;
end.
And here is our unit that contains the tests.
unit sample_tests;
{$mode objfpc}{$H+}
interface
uses
TestFramework;
type
TTestCaseFirst = class(TTestCase)
published
procedure TestWarning;
procedure TestOne;
procedure TestTwo;
procedure TestThree;
end;
implementation
uses
sysutils;
{ TTestCaseFirst }
procedure TTestCaseFirst.TestWarning;
begin
// Do nothing here - should cause a Warning
end;
procedure TTestCaseFirst.TestOne;
begin
Check(1 + 1 = 3, 'Catastrophic arithmetic failure!');
end;
procedure TTestCaseFirst.TestTwo;
begin
Check(1 + 1 = 2, 'Catastrophic arithmetic failure!');
end;
procedure TTestCaseFirst.TestThree;
var
s: string;
begin
s := 'hello';
CheckEquals('Hello', s, 'Failed CheckEquals');
end;
initialization
TestFramework.RegisterTest(TTestCaseFirst.Suite);
end.
For further reading I recommend the book
Test Driven Development: By Example by Kent Beck.
I hope that helps. If you have any more questions on FPTest, feel free to join the dedicated support newsgroup.
NNTP Server:
geldenhuys.co.uk Port:
119 Newsgroup:
fptest.support