Can I pass a set to a test case in DUnitX?

后端 未结 2 1641
眼角桃花
眼角桃花 2021-02-07 06:20

I\'m trying to check the state of an object after running a test. This state is contained in a set. Is it possible to pass the expected state to the test case using DUnitX Attri

2条回答
  •  遥遥无期
    2021-02-07 06:57

    You are using TestCaseAttribute to specify the arguments to be passed to your test method. However, it simply does not offer any support for passing sets as arguments. You can see that this is so by looking at the constant Conversions declared in the DUnitX.Utils unit. It maps any conversion to a set to ConvFail.

    So, if you want to specify this data using attributes you are going to need to extend the testing framework. You could derive your own descendent from CustomTestCaseSourceAttribute and override GetCaseInfoArray to decode your set arguments. As a crude example, you could use this:

    type
      MyTestCaseAttribute = class(CustomTestCaseSourceAttribute)
      private
        FCaseInfo: TestCaseInfoArray;
      protected
        function GetCaseInfoArray: TestCaseInfoArray; override;
      public
        constructor Create(const ACaseName: string; const AInput: string; const AExpectedResult: TResultSet);
      end;
    
    constructor MyTestCaseAttribute.Create(const ACaseName, AInput: string; const AExpectedResult: TResultSet);
    begin
      inherited Create;
      SetLength(FCaseInfo, 1);
      FCaseInfo[0].Name := ACaseName;
      SetLength(FCaseInfo[0].Values, 2);
      FCaseInfo[0].Values[0] := TValue.From(AInput);
      FCaseInfo[0].Values[1] := TValue.From(AExpectedResult);
    end;
    
    function MyTestCaseAttribute.GetCaseInfoArray: TestCaseInfoArray;
    begin
      Result := FCaseInfo;
    end;
    

    You can then add the following attribute to your test method:

    [MyTestCase('Demo2', 'InputB', [resWarn])]
    procedure Test(Input: string; ExpectedResult: TResultSet);
    

    I've avoided using RTTI here for simplicity, but using RTTI would give you more flexibility. You'd pass the argument as a string, and decode it using RTTI, just as the code in DUnitX does. This means you don't need to write bespoke attributes every time you want to use a set argument.

    Even better would be to implement this within DUnitX by extending the Conversions map to cover sets, and submit this as a patch. I'm sure others would find it useful.

提交回复
热议问题