How to access fields of a TTestCase in a TTestSetup class

后端 未结 7 1245
死守一世寂寞
死守一世寂寞 2021-02-07 13:37

I am creating unit tests with DUnit. I have a class that takes quite a long time to initialize.

I derive a class TMyTestSetup from TTestSetup and override its Setup met

7条回答
  •  无人及你
    2021-02-07 14:07

    You can't initialize TTestCase fields for a whole test suite, and here is an explanation why:

    unit Tests3;
    
    interface
    
    uses
      TestFramework, TestExtensions, Windows, Forms, Dialogs, Controls, Classes,
      SysUtils, Variants, Graphics, Messages;
    
    type
      TMyTestCase = class(TTestCase)
      private
        FValue: Integer;
      published
        procedure Test1;
        procedure Test2;
      end;
    
    implementation
    
    { TMyTestCase }
    
    procedure TMyTestCase.Test1;
    begin
      FValue:= 99;
      ShowMessage(Format('%p, %d', [Pointer(Self), FValue]));
    end;
    
    procedure TMyTestCase.Test2;
    begin
      ShowMessage(Format('%p, %d', [Pointer(Self), FValue]));
    end;
    
    initialization
      RegisterTest(TMyTestCase.Suite);
    end.
    

    If you run the above unit test you will see that the 'Self' addresses shown in Test1 and Test2 methods are different. That means that TMyTestCase object instances are different for Test1 and Test2 calls.

    Consequently, any fields you may declare in TMyTestCase class are volatile between test method's calls.

    To perform "global" initialization you should declare your object globally, not as TMyTestCase field.

提交回复
热议问题