Delphi DUnitX tests creation of form twice

333 views Asked by At

I created a TestCase with DUnitX which automatically generated some code and I'm confused as to how I should structure the test case.

The (automatically generated) code looks like the following:

procedure TestTBtnMgmtForm.SetUp;
begin
  FBtnMgmtForm := TBtnMgmtForm.Create;
end;

procedure TestTBtnMgmtForm.TearDown;
begin
  FBtnMgmtForm.Free;
  FBtnMgmtForm := nil;
end;

procedure TestTBtnMgmtForm.TestFormCreate;
var
  Sender: TObject;
begin
  // TODO: Setup method call parameters
  FBtnMgmtForm.FormCreate(Sender);
  // TODO: Validate method results
end;

However, TBtnMgmtForm.Create will automatically call .FormCreate. Is it good practice to separate these two somehow? What is the difference or should be the difference between .Create and .FormCreate?

1

There are 1 answers

2
David Heffernan On

The constructor of a form will call the OnCreate event handler, if it is assigned. In your case it is assigned, to the function named FormCreate.

As a general rule, event handlers are invoked by the framework and should not be called directly. I can't see enough of your code to be sure but my instincts tell me that you should not be calling FormCreate at all. It is the job of the framework to do that.

The point of OnCreate is that it allows you to inject code into the constructor of the form class without having to override the constructor. You can use the form designer to add the event handler and fill in the code. Personally I regard OnCreate as somewhat facile. Once you know how to override constructors it seems more explicit to do that.

You however appear to have a form with a parameterless constructor. That is odd. Usually you would override the virtual constructor declared in TComponent. I wonder why you are not doing that.