Reputation:
I found this older post which faces the same problem: How to mock a QML component
Unfortunately, there's no solution. To recap the problem:
I have a QML TestCase
which imports a module. But this module relies on a root context property which normally would be added in the main.cpp
. Since this is a TestCase
, I have no influence on how the QQmlApplicationEngine
starts up.
How can I add the missing context property?
Upvotes: 7
Views: 665
Reputation: 66
If your module relies on a root context property, you should think to create a c++ Plugin for QML using QQmlEngineExtensionPlugin
If you take a look at the implementation you will need to reimplement the following function:
void initializeEngine(QQmlEngine *engine, const char *uri) override;
As the documentation says:
Initializes the extension from the uri using the engine. Here an application plugin might, for example, expose some data or objects to QML, as context properties on the engine's root context.
In this function you can put your required root context property
void initializeEngine(QQmlEngine *engine, const char *uri) override
{
MyObject* object = new MyObject(engine->rootContext());
engine->rootContext()->setContextProperty("myProperty", object);
}
After that, you just need to import your QML module in your QML file, where you TestCase is defined and you won't need to use any main functions to add this object as root context property.
Upvotes: 1
Reputation: 397
Edit:
In Qt 5.11, there is a new chapter in Qml UnitTesting. See chapter Executing C++ Before QML Tests.
Previous answer:
You can get the instance of QQmlEngine by passing QML item to C++ side, where you can use method qmlEngine.
So, you are able to set context property by calling
qmlEngine(passedQmlItem)->rootContext()->setContextProperty("propertyName", propertyValue);
Upvotes: 0