I have to unit tests some forms in Delphi. My boss wants me to write tests to check if events are assigned. There are so many that we have to run some checks on them.
For example, I want to check that
TMyForm.OnCreate = TMyForm.FormCreate.
To do this, I wrote :
function TFMaitreTest.SameMethod(const Method1, Method2: TNotifyEvent; msg : string = ''): boolean;
begin
Assert.IsTrue(TEqualityComparer<TNotifyEvent>.Default.Equals(Method1, Method2), msg);
end;
But using this way, I have to override the SameMethod
for every kind of event delegate : TNotifyEvent, TDataSetEvent, ...
I then thought of using generics, as such :
function TFMaitreTest.SameMethod<T>(const Method1, Method2: T; msg : string = ''): boolean;
But this does not compile. TEqualityComparer
needs some Generic constraint, but a generic constraint cannot be defined for a procedure of object. Using TMethod
as a constraint does not work either. Maybe there's a way here, but I have not found it.
Then, I thought of changing approach altogether using Rtti. I want to compare the methods using Rtti, but for that, I have to know the name of the method with a string.
RttiType.GetMethod(methodName)
Here, methodName
is a pure string. If we refactor and methodName
becomes MyMethod
, we're kind of screwed and have to check manually everywhere this string is used. We would like to have compile time errors. It's less error prone.
C# has the concept of lambda expressions which is very powerful for these kind of scenarios :
See Get the name of a method using an expression
How can I write a more generic way of testing if an event property is assigned to a specific procedure, without having to write a method for every event kind ?
Thank you for your help.