Qual è il modo migliore per scrivere un test DUit di Delphi per un discendente TThread quando FreeOnTerminate = True? Il discendente TThread restituisce un riferimento che ho bisogno di testare per, ma non riesco a capire come attendere per il thread per finire nel test ...Test unità Delphi per TThread con FreeOnTerminate = True
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.
Tutte le idee sarebbe il benvenuto.
Delphi 2010.
Grazie per la risposta Rob. Non ho avuto il tempo di testare la soluzione, ma ci proverò domani. –
Ciao Rob, grazie la tua risposta sembra funzionare alla grande. Ho accettato questa come risposta. Inoltre, c'era una risposta interessante pubblicata qui sotto usando thread anonimi. Sono ancora su Delphi 2010, quindi non ho accesso ad esso, ma sembra una soluzione elegante. Verificherò anche questo una volta che avrò aggiornato. Saluti. –