justyy
justyy

Reputation: 6041

dataProvider in DUnit Delphi?

How to provide data for Unit Tests in Delphi DUnit) ? For example, in PHP, you can do something like this:

  public function URLProvider() {
    return [
      ["https://helloacm.com"],
      ["https://codingforspeed.com"]
    ];
  }

  /**
   * @dataProvider URLProvider
   */  
  public function test_url($url) {
    $data = file_get_contents("$this->API?url=$url");
    $result = json_decode($data, true);
    $this->assertEquals(true, $result['result']);
    $this->assertEquals(200, $result['code']);
  }

Upvotes: 2

Views: 243

Answers (2)

Stefan Glienke
Stefan Glienke

Reputation: 21713

With Spring4D DUnit extensions you can write something like that (look into the release/1.2 branch in the Tests\Source folder for the unit Spring.Testing).

program Tests;

uses
  Spring.Testing,
  TestInsight.DUnit;

type
  TUrlTests = class(TTestCase)
  public
    class function UrlProvider: TArray<string>; static;
  published
    [TestCaseSource('UrlProvider')]
    procedure TestUrl(const url: string);
  end;

{ TUrlTests }

procedure TUrlTests.TestUrl(const url: string);
begin
  // do whatever
end;

class function TUrlTests.UrlProvider: TArray<string>;
begin
  Result := ['https://helloacm.com', 'https://codingforspeed.com'];
end;

begin
  TUrlTests.Register;
  RunRegisteredTests;
end.

You can either pass the name to the method within the same Testcase class or specify another class - the method itself must be a public static class function. The extension then will create different test cases for each parameter being passed. You can check the Unittests of Spring4D for other use cases.

Upvotes: 3

Wosi
Wosi

Reputation: 45233

In DUnit every single test case has to be a procedure without parameters. So there can't exist a mechanism for injecting arguments via custom attributes to test methods like you are doing it PHPUnit.

You should take a look at DUnitX instead where you can define tests like this:

[TestCase('https://helloacm.com')]
[TestCase('https://codingforspeed.com']
procedure TestUrl(const Url: String); 

Upvotes: 2

Related Questions