Search code examples
delphitestingdunitx

Delphi DunitX, how do I get the name of the test currently running?


How do I get the name of the test that is currently running in DunitX?

For example:

procedure TestModule.TestProcedure;
begin
  Assert.Pass('This tests name is ' + TestName);
end

Solution

  • You will need to create an instance of an ITestLogger and add this to the current runner:

    TDUnitX.CurrentRunner().AddLogger(myLogger);
    

    The ITestLogger has a lot of methods that allows for reading out a lot of detailed information. DUnitX comes with a variety of loggers, but there isn't really anything that fits our use case here.

    I suggest to

    1. Create a new class, derive from TDUnitXNullLogger from DUnitX.Loggers.Null
    2. Override the virtual method procedure OnBeginTest(const threadId: TThreadID; const Test: ITestInfo);
    3. Save Test.MethodName for later use

    An instance of your new class could be created in the SetUpFixture method of your test case.

    Caveat: You can add your logger to TDUnitX.CurrentRunner() but I have found no public way of removing it when it is no longer needed.

    Here is the complete example:

    unit Unit1;
    
    interface uses DUnitX.TestFramework;
    
    type
        [TestFixture]
        TMyTest = class
        private var
            myLogger: ITestLogger;
        protected
            function getCurrentTestName(): String;
        public
            [SetupFixture] procedure SetupFixture();
            [Test] procedure TestName();
        end;
    
    implementation uses DUnitX.Loggers.Null;
    
    type
        TMyLogger = class(TDUnitXNullLogger)
            protected procedure OnBeginTest(
                const threadId: TThreadID;
                const Test: ITestInfo
            ); override;
            public var testInfo: ITestInfo;
        end;
    
    function TMyTest.getCurrentTestName(): String;
    begin
        Result := TMyLogger(myLogger).testInfo.MethodName;
    end;
    
    procedure TMyTest.SetupFixture();
    begin
        myLogger := TMyLogger.Create();
        TDUnitX.CurrentRunner().AddLogger(myLogger);
    end;
    
    procedure TMyTest.TestName();
    begin
        const expected = 'TestName';
        var actual := getCurrentTestName();
        Assert.AreEqual(expected, actual);
    end;
    
    { TMyLogger }
    
    procedure TMyLogger.OnBeginTest(const threadId: TThreadID; const Test: ITestInfo);
    begin
        testInfo := Test;
    end;
    
    initialization
        TDUnitX.RegisterTestFixture(TMyTest);
    end.