Search code examples
delphiunit-testingtestingdunit

How can I test functions and procedures as they don't belong to classes in Delphi?


I have several little functions in an old Unit called Utils.pas.

Now I'd like refactoring some of them, but I think it's better to write test before. With DUnit I think it's impossible without a class.

So I'd like to know how can I test them before refactoring?

Edit:

I thought it was impossible because I was trying to add a test case in Delphi using Test Case Wizard. See the picture bellow that there aren't any classes and methods, so I'm not be able to create it.

enter image description here


Solution

  • You can't test a standalone function using the wizard but it's not a problem to test a standalone function with DUnit.

    Example

      //***** A Standalone function te be tested in a unit far, far away
      function Add(v1, v2: Integer): Integer;
      ...
    
      //***** A testclass to contain the testmethods calling our 
      //      standalone function     
      TTestAdd = class(TTestcase)
      published
        procedure AddingComplement_ShouldEqualZero;
        procedure AddingNegativeNumbers_ShouldBeLessThanZero
        ...
      end;
    
      implementation
    
      procedure TTestAdd.AddingComplement_ShouldEqualZero;
      begin
        // Setup, Execute & Verify
        CheckEquals(0, Utils.Add(-1, 1), 'Complement doesn''t add to zero');
      end;
    
      procedure TTestAdd.AddingNegativeNumbers_ShouldBeLessThanZero
      begin
        // Setup, Execute & Verify
        CheckEquals(-3, Utils.Add(-1, -2), 'Add doesn''t add');
      end;