How to access fields of a TTestCase in a TTestSetup class

后端 未结 7 1248
死守一世寂寞
死守一世寂寞 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:12

    Using TTestSetup you could do something like this:

    type
      TMyTestSetup = class(TTestSetup)
      private
        FValue: Integer;
      protected
        procedure SetUp; override;
        procedure TearDown; override;
      end;
    
      TMyTestCase = class(TTestCase)
      published
        procedure TestSomething;
      end;
    
    var
      TestSetup: TMyTestSetup;
    
    procedure TMyTestSetup.SetUp;
    begin
      inherited;
      TestSetup := Self;
      FValue := 42;
    end;
    
    procedure TMyTestSetup.TearDown;
    begin
      TestSetup := nil;
      inherited;
    end;
    
    procedure TMyTestCase.TestSomething;
    begin
      CheckEquals(TestSetup.FValue, 42);
    end;
    
    initialization
      TestFramework.RegisterTest(TMyTestSetup.Create(
        TTestSuite.Create('My test suite', [TMyTestCase.Suite])
      ));
    

    It feels somewhat revolting mind you, but it does the job!

提交回复
热议问题