Home > OS >  How to Inject Mocks in FlaUI/WPF Window?
How to Inject Mocks in FlaUI/WPF Window?

Time:04-27

In my WPF app, I have a MainWindow.xaml and a related MainWindow.xaml.cs. The latter has a property DatabaseAccessor which accesses a database:

public partial class MainWindow : System.Windows.Window
{
    public IDatabaseAccessor DatabaseAccessor { get; set; }

    public MainWindow()
    {
        InitializeComponent();
        DatabaseAccessor = new RealDatabaseAccessor();
    }

    // [...]
}

Now I'm writing a test using FlaUI. In my test I'm writing something like

using FlaUI.UIA3;
using Moq;

var app = FlaUI.Core.Application.Launch("myapp.exe");
using (var automation = new UIA3Automation())
{
    FlaUI.Core.AutomationElements.Window window = app.GetMainWindow(automation);

    //// I am looking for a way to do something like this (but no such API exists):
    // MainWindow myWindow = (MainWindow) window.RealWindow;
    // myWindow.DatabaseAccessor = new Mock<IDatabaseAccessor>().Object;
}

For my tests, I do not want to communicate with the real database but mock it, instead.

How can I inject a mocked DatabaseAccessor into the Window opened with FlatUI (see the commented code in my last snippet)? Or in other words: How can I access the System.Windows.Window for a given FlaUI.Core.AutomationElements.Window?

If this is not possible, how would you approach such a problem?

CodePudding user response:

You need to rethink what you are doing here.

An UI automation test is not supposed to mock dependencies. It starts your app in a separate process and interacts with it using the actual elements that are presented on the screen.

If you want to test a specific component in your code, you should write a unit test against this component. You can then mock any external dependencies.

  • Related