Search code examples
delphivcl

EInvalidOperation (no parent window) when creating a TFrame in a unit-testing (and therefore console) application


Now, I'm writing a unit test for a TFrame-derrived class...

In my Setup method, I got the following code:

procedure TestFixtureClass.Setup;
begin
    FTestContainer := TContainer.Create;

    FTestContainer.RegisterType<TframeClass, TframeClass>
        .Implements<IFrameClass>
        .AsSingleton(TRefCounting.True)
        .DelegateTo(function: TframeClass 
            begin
                // also tried: TframeClass.Create(Application);
                // and: form1 := TForm1.Create(Application); TframeClass.Create(form1);
                Result := TframeClass.Create(nil);
            end)
        .AsDefault;

    FTestContainer.Build;

    FSut := FTestContainer.Resolve<IFrameClass>;  // Exception here
end;

TframeClass has reference counting (similar to TInterfacedObject), thats why I use TRefCounting.True in AsSingleton.

But now I got the following problem: Exception EInvalidoperation: 'Element has no parent window'.

The above TFrameClass works in the production application, but it raises the exception in the test application.

Is there a possibility to get this work, keeping the SUT (system-under-test) a TFrame-derrived class?


Solution

  • I've found the answer on my own...

    It was no spring4d nor a real dunitx problem...

    It is just, that you normally cannot create a frame in a console application (which my testing app is).

    In a Console Application, Application.Handle is 0... and thats why TFrame cannot get a Handle...

    So, I use a little hack (which I can accept for a non-productional testing application):

    Application.Handle := GetConsoleWindow;
    

    in the main (*.dpr) unit.

    Then, it works.