How to check functions and procedures since they do not belong to classes in Delphi?

I have several small functions in an old group called Utils.pas .

Now I would like to refactor some of them, but I think it's better to write a test earlier. With DUnit, I find it impossible without a class.

So, I would like to know how I can test them before refactoring?

Edit:

I thought this was not possible because I was trying to add a test case to Delphi using the Test Case Wizard. See the figure below that there are no classes and methods, so I cannot create it.

enter image description here

+6
source share
3 answers

You cannot test a stand-alone function using the wizard, but it is not a problem to test a stand-alone function using 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; 
+7
source

AFAICT, DUnit does not require code verification as class methods. Only the tests themselves should be classes.

EDIT . The wizard is just convenient. You do not have to use it.

+8
source

It is necessary to maintain real code. There are assumptions in real code that have not been well documented. This code has been modified by people who forget or never know these assumptions. Trust the test, do not trust the code.

Real TDD allows you to create an object and its methods before implementation. You need a clear model before you can write a test case.

So, generate object (s), add methods, parameters, etc. Perhaps using UML2 would be better, then write test cases for them, and then implement the objects. After that, run the profiler and find out how terrible your code and refactoring is.

As a general solution, it is almost always better to write a factory object to create and initialize your objects. The closer you get to the core functionality, the more it becomes important.

Write tests for expected failures and exceptions. use validation to make sure.

Finally, write each test and see how it works before writing code to make it successful.

+1
source

Source: https://habr.com/ru/post/890491/


All Articles