title: Delphi unit test for a TThread with FreeOnTerminate = True
body: <p>What is the best way to write a Delphi DUnit test for a TThread descendant when FreeOnTerminate = True? The TThread descendant returns a reference which I need to test for, but I can't figure out how to wait for the thread to finish in the test...</p>
  
  <pre><code>unit uThreadTests;
  
  interface
  
  uses
    Classes, TestFramework;
  
  type
  
    TMyThread = class(TThread)
    strict private
      FId: Integer;
    protected
      procedure Execute; override;
    public
      constructor Create(AId: Integer);
      property Id: Integer read FId;
    end;
  
    TestTMyThread = class(TTestCase)
    strict private
      FMyId: Integer;
      procedure OnThreadTerminate(Sender: TObject);
    protected
      procedure SetUp; override;
      procedure TearDown; override;
    published
      procedure TestMyThread;
    end;
  
  implementation
  
  { TMyThread }
  
  constructor TMyThread.Create(AId: Integer);
  begin
    FreeOnTerminate := True;
    FId := AId;
  
    inherited Create(False);
  end;
  
  procedure TMyThread.Execute;
  begin
    inherited;
  
    FId := FId + 1;
  end;
  
  { TestTMyThread }
  
  procedure TestTMyThread.TestMyThread;
  //var
  //  LThread: TMyThread;
  begin
  //  LThread := TMyThread.Create(1);
  //  LThread.OnTerminate := OnThreadTerminate;
  //  LThread.WaitFor;
  //  CheckEquals(2, FMyId);
  //  LThread.Free;
  ///// The above commented out code is only useful of FreeOnTerminate = False;
  
    with TMyThread.Create(1) do
    begin
      OnTerminate := OnThreadTerminate;
      WaitFor; /// Not sure how else to wait for the thread to finish?
    end;
  
    CheckEquals(2, FMyId);
  end;
  
  procedure TestTMyThread.OnThreadTerminate(Sender: TObject);
  begin
    FMyId := (Sender as TMyThread).Id;
  end;  /// When FreeOnTerminate = True - THIS LINE CAUSES ERROR: Thread Error the handle is invalid
  
  procedure TestTMyThread.SetUp;
  begin
    inherited;
  
  end;
  
  procedure TestTMyThread.TearDown;
  begin
    inherited;
  
  end;
  
  initialization
    RegisterTests([TestTMyThread.Suite]);
  
  
  end.
  </code></pre>
  
  <p>Any ideas would be welcomed. </p>
  
  <p>Delphi 2010.</p>