Home > Back-end >  How to do a test with an anonymous with Delphi and TestInsight?
How to do a test with an anonymous with Delphi and TestInsight?

Time:12-20

I want to test a procedure with an anonymous methode. The function uses an anonymousThread to execute a rest request. It returns synchronized via the anonymous method.

How do I do this?

I’m using TestInsight and have this.

// Calls a rest threaded request
procedure Shows.GetAgenda;
begin
  var testCompleted := false;
  DmShows.LoadShows(120,
  procedure (ServerResult : TServerResult)
  begin

    try
      Assert.IsTrue(ServerResult.StatusCode = 200, ServerResult.Message);
      Assert.IsTrue(DmShows.TableShows.RecordCount > 0, 'No shows found for testing.');
    finally
      TestCompleted := true;
    end;

  end);

  while not testCompleted do
  begin
    TThread.Sleep(10);
    Application.ProcessMessages();
  end;


end;

This example throws an exception in CheckSynchronize on the first Assert. The anonymous method was synchronized.

CodePudding user response:

You cannot run testing framework validation methods from within anonymous method used as a callback as testing framework will not be able to catch those exceptions properly.

You need to introduce additional variables, assign the appropriate values you wish to validate inside the callback, and then after the callback is called and the testCompleted flag was set, validate the results.

I am not sure whether you have access to the Application if you are running through TestInsight, so I replaced Application.ProcessMessages with CheckSynchronize call, which is what you actually need for processing of the synchronized code. This enables proper testing if you run DUnitX from console.

If you have access to the Application instance within TestInsight, you can leave Application.ProcessMessages, but in that case you cannot use console.

procedure Shows.GetAgenda;
begin
  var testCompleted := false;
  var StatusCode := 0;
  var StatusMessage := '';
  var RecordCount := 0;

  DmShows.LoadShows(120,
  procedure (ServerResult : TServerResult)
  begin
    try
      StatusCode := ServerResult.StatusCode;
      StatusMessage := ServerResult.Message;
      RecordCount := DmShows.TableShows.RecordCount;
    finally
      TestCompleted := true;
    end;
  end);

  while not testCompleted do
  begin
    TThread.Sleep(10);
    CheckSynchronize(1000);
  end;

  Assert.IsTrue(StatusCode = 200, StatusMessage);
  Assert.IsTrue(RecordCount > 0, 'No shows found for testing.');    
end;
  • Related