Search code examples
c++unreal

Stub Class for Testing is not being instantiated - Unreal


I'm working on a project in Unreal Engine 5.3 where I have a base class UMapViewer derived from UUserWidget. This base class has a method GetAspectRatio(). I have created a derived class MapViewerTestHelper that overrides this method for unit testing. Below I have posted a simple version of the AspectRatio Methods for the base class, the derived class and finally a snippet of calling the derived classes method, it should give me a value of 5.0 but the test returns a value of 10.0

UCLASS()
class VORONOIMAP_API UMapViewer : public UUserWidget {
    GENERATED_BODY()
public:
    explicit UMapViewer(const FObjectInitializer& ObjectInitializer);
    virtual void NativeConstruct() override;
    virtual float GetAspectRatio() const {
        return 10.0;
    }
}; 

class MapViewerTestHelper : public UMapViewer {
public:
    MapViewerTestHelper(const FObjectInitializer& ObjectInitializer) : UMapViewer(ObjectInitializer) {}
    virtual float GetAspectRatio() const override {
        return 5.0;
    }


It("should correctly calculate the aspect ratio", [this]() {
    MapViewerTestHelper* TestViewer = NewObject<MapViewerTestHelper>();
    const float CalculatedAspectRatio = TestViewer->GetAspectRatio(); 
    TestEqual("This Should retunr 5.0", CalculatedAspectRatio, 5.0);
});
};


Solution

  • After a bit more debugging, I found that my class that was being instantiated was not the stub class but was rather the base class, this was really weird behavior since I wasn't doing any type of casting, but I found this by doing a simple log in the constructor of the base class and the derived/inherited class, after doing some more research, I came to know about the reflection system in unreal. From what I understand it's how unreal does its memory allocation. My class was built for testing, so I put it in the test file, but unreal does "reflect" in these test files so after I moved my stub class to the same file as my base class it worked fine with no issues. Hopefully this helps somebody else.