RED MONKEY
RED MONKEY

Reputation: 3153

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

Upvotes: 2

Views: 443

Answers (2)

Dave Craggs
Dave Craggs

Reputation: 37

Better to use:

Result := TJPANUllLogger(myLogger).testInfo.Name;

As this give the name of the test rather than just the method name.

Upvotes: 1

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.

Upvotes: 4

Related Questions