Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
GimmeJob
Sign in
Test automation · Desktop Automation Example · Chapter 03 / 04

Test automation learning path

C# + NUnit + FlaUI

Study the same desktop-automation concepts in .NET and see how test intent is separated from reusable NUnit/FlaUI framework mechanics.

.NET implementation: NUnit + FlaUI/UIA3

The .NET implementation demonstrates the same automation model with a more explicit framework layer. NotepadTests contains test intent: enter text, replace text, copy/paste, save and assert. NotepadTestBase contains reusable mechanics: create and delete test files, start Notepad, discover the correct window, locate the editor, operate the clipboard, synchronize, capture evidence and clean up.

That separation is important. A test method should describe the scenario being verified; operating-system details belong in reusable framework code unless the OS behavior itself is the subject of the test. NUnit's [SetUp] and [TearDown] provide the lifecycle boundary, while FlaUI's UIA3Automation is the bridge into the same Windows UI Automation model used by the Python implementation.

When comparing Python and C#, focus on equivalence rather than syntax: pytest fixture ↔ NUnit setup/teardown, pywinauto Desktop(backend="uia") ↔ FlaUI UIA3Automation, polling helper ↔ retry/wait helper, and UI/file assertions ↔ the same two layers of verification.

The .NET test project file is executable configuration

Read the `.csproj` as the declaration that makes NUnit, FlaUI and Windows APIs available.

Concept

Unlike Python's requirements.txt, the project file also controls compilation/runtime features. It is both dependency declaration and build configuration.

Code from the project

Reviewed source: `flaui/Notepad.Tests/Notepad.Tests.csproj`


<PropertyGroup>
  <TargetFramework>net8.0-windows</TargetFramework>
  <ImplicitUsings>enable</ImplicitUsings>
  <Nullable>enable</Nullable>
  <IsTestProject>true</IsTestProject>
  <UseWindowsForms>true</UseWindowsForms>
</PropertyGroup>

<ItemGroup>
  <PackageReference Include="Allure.NUnit" Version="2.15.0" />
  <PackageReference Include="FlaUI.Core" Version="5.0.0" />
  <PackageReference Include="FlaUI.UIA3" Version="5.0.0" />
  <PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.9.0" />
  <PackageReference Include="NUnit" Version="4.6.1" />
  <PackageReference Include="NUnit3TestAdapter" Version="6.3.0" />
</ItemGroup>

Detailed explanation

MSBuild reads this file before compilation. The Windows target framework enables Windows-specific APIs, IsTestProject marks the project as tests, Windows Forms support is needed for clipboard/input-language helpers, and the package references provide the test SDK/adapter, NUnit API, FlaUI core/UIA3 implementation and Allure integration.

Initially, source files reference unknown packages. Once this step completes, the .NET test assembly can compile and dotnet test can discover it through the test SDK/adapter.

Design reasoning

Removing NUnit3TestAdapter or the test SDK can make tests undiscoverable; removing FlaUI.UIA3 removes the backend implementation; removing Windows Forms breaks clipboard helpers used by the base class.

Key points

  • A .csproj controls more than packages.
  • Runner discovery depends on the test SDK/adapter as well as NUnit itself.

Common pitfalls

  • Assuming NUnit package alone is sufficient for dotnet test discovery.

NUnit BaseSetUp: create the per-test application state

Compare the C# lifecycle with the pytest fixture you already traced.

Concept

This is the C# equivalent of fixture setup: scenario tests inherit a prepared, isolated Notepad document without duplicating lifecycle mechanics.

Code from the project

Reviewed source: `flaui/Notepad.Tests/NotepadTestBase.cs`


[SetUp]
public void BaseSetUp()
{
    _automation = new UIA3Automation();
    _tempFilePath = Path.Combine(
        Path.GetTempPath(),
        $"{TempFilePrefix}{Guid.NewGuid():N}.txt");
    File.WriteAllText(_tempFilePath, InitialText);

    Process.Start(new ProcessStartInfo
    {
        FileName = "notepad.exe",
        Arguments = $"\"{_tempFilePath}\"",
        UseShellExecute = true
    })?.Dispose();

    var expectedFileName = Path.GetFileName(_tempFilePath);
    var windowResult = Retry.WhileNull(
        () => FindNotepadWindow(_automation, expectedFileName),
        timeout: TimeSpan.FromSeconds(15),
        interval: TimeSpan.FromMilliseconds(250),
        ignoreException: true);

    _window = windowResult.Result;
    _notepadProcessId = _window.Properties.ProcessId.Value;
}

Detailed explanation

Before each NUnit test, the base class creates a UIA3 automation client, generates a GUID-based temporary filename, writes initial content, launches Notepad, then uses FlaUI's retry helper to locate the window containing that filename. The discovered window and process ID are stored in instance fields for the scenario and later teardown.

Initially, no UIA client or test file. Once this step completes, the base object owns UI automation, a unique file, a discovered Notepad window and its current process ID.

Design reasoning

If the window search is removed and code relies only on Process.Start, modern Notepad process/tab reuse can associate the test with the wrong UI object.

Key points

  • NUnit [SetUp] and pytest fixture setup solve the same lifecycle problem differently.
  • GUID filenames create test identity.

Common pitfalls

  • Treating process creation as proof that the expected UI is ready.

NUnit BaseTearDown: clean only what the test owns

Study defensive cleanup in a shared desktop application that may contain unrelated tabs.

Concept

Desktop tests run against shared operating-system state. Cleanup must be scoped to resources the test created; killing notepad.exe globally would be destructive and could affect another test or a user session.

Code from the project

Reviewed source: `flaui/Notepad.Tests/NotepadTestBase.cs`


[TearDown]
public void BaseTearDown()
{
    var testDocumentClosed = false;

    try
    {
        CaptureWindow("99-final");
        BeforeClosingTestDocument();

        if (_window is not null)
        {
            var editor = FindEditor(_window);
            editor.Focus();
            Keyboard.TypeSimultaneously(VirtualKeyShort.CONTROL, VirtualKeyShort.KEY_W);
            Thread.Sleep(250);
            TryDiscardUnsavedChanges();
            testDocumentClosed = WaitUntilTestFileIsNoLongerOpen(TimeSpan.FromSeconds(3));
        }
    }
    finally
    {
        if (_tempFilePath is not null && (testDocumentClosed || !IsTestFileOpen()))
        {
            File.Delete(_tempFilePath);
        }
        _automation?.Dispose();
    }
}

Detailed explanation

After each test, NUnit invokes teardown inherited from the base class. It captures final evidence, gives specialized tests a hook, focuses the test editor and sends Ctrl+W to close that document/tab rather than killing all Notepad. If an unsaved-changes dialog appears it tries to discard it, waits until the unique file is no longer open, then deletes only that temporary file and disposes UIA resources.

Initially, the test document may be saved or dirty and UIA objects are alive. Once this step completes, the owned tab/file is gone and the automation client is disposed, while unrelated Notepad state is left alone.

Design reasoning

Replacing Ctrl+W with killing all Notepad processes violates ownership. Deleting the file before confirming the document is closed can race with the application and make cleanup unreliable.

Key points

  • Cleanup is part of test correctness.
  • Own the smallest possible external resource.

Common pitfalls

  • Using process-wide cleanup for a tab-scoped test.

FlaUI scenario code stays small because the base owns mechanics

Separate scenario intent from reusable desktop-automation infrastructure.

Concept

The test method reads as business/test intent because low-level UI discovery, timing, clipboard STA handling, screenshots and cleanup are centralized. This is the practical purpose of a test base/framework abstraction.

Code from the project

Reviewed source: `flaui/Notepad.Tests/NotepadTests.cs`


[Test]
[Category("PortableNotepad")]
public void CanTypeAndSaveText()
{
    const string expected = "Hello desktop automation";

    var editor = FindEditor();
    ReplaceTextWithClipboard(editor, expected);
    CaptureWindow("01-text-entered");

    Assert.That(ReadEditorText(editor), Is.EqualTo(expected));

    SaveAndWaitForText(expected);
    CaptureWindow("02-saved");

    Assert.That(File.ReadAllText(TestFilePath), Is.EqualTo(expected));
}

Detailed explanation

NUnit calls inherited setup before entering this method. The scenario asks the base class for the editor, replaces text through the shared clipboard strategy, records evidence and checks the UI value. It then performs the shared save-and-wait action and independently verifies disk contents. Inherited teardown runs after the method.

Initially, setup prepared an empty unique document. Once this step completes, exact text has been validated in the editor and on disk; teardown then removes the owned resources.

Design reasoning

Inlining every helper here would duplicate complex mechanics across scenarios and make behavior harder to change consistently.

Key points

  • Tests express intent; framework helpers express mechanics.
  • The assertions remain visible in the scenario.

Common pitfalls

  • Hiding all assertions inside helpers until the test no longer communicates what it proves.

FlaUI UIA3 is a client over the Windows UI Automation tree

Connect the C# wrapper API to the same operating-system automation model used by pywinauto.

Concept

FlaUI and pywinauto are different client libraries over the same Windows UIA concepts. Understanding UIA itself makes the libraries easier to compare and prevents library-specific memorization.

Code from the project

Reviewed source: `flaui/Notepad.Tests/NotepadTestBase.cs`


private static FlaUITextBox FindEditor(Window window)
{
    var result = Retry.WhileNull(
        () => window.FindFirstDescendant(cf => cf.ByControlType(ControlType.Document))
              ?? window.FindFirstDescendant(cf => cf.ByControlType(ControlType.Edit)),
        timeout: TimeSpan.FromSeconds(10),
        interval: TimeSpan.FromMilliseconds(250),
        ignoreException: true);

    if (!result.Success || result.Result is null)
    {
        throw new InvalidOperationException(
            "Could not find the Notepad editor through UI Automation.");
    }

    return result.Result.AsTextBox();
}

Detailed explanation

Starting from a FlaUI Window, the helper queries descendants in the Windows UI Automation tree. It first asks for a Document control, then falls back to Edit, retries while the UI is still materializing, validates that a result exists and converts the generic automation element into FlaUI's text-box wrapper.

Initially, generic top-level Window. Once this step completes, a typed FlaUI TextBox wrapper for the semantic text editor.

Design reasoning

Removing the fallback can make one Windows build unsupported. Removing retry assumes the UI tree is fully available immediately after launch.

Key points

  • Libraries wrap UIA; they do not replace the underlying model.
  • Typed wrappers are created after element discovery.

Common pitfalls

  • Learning FindFirstDescendant without understanding what a UIA descendant is.

Compare Python and C# by responsibility, not syntax

Collapse two implementations into one shared automation mental model.

Concept

Framework knowledge transfers when you understand responsibilities. Memorizing pytest.fixture or [SetUp] alone does not teach lifecycle design; seeing them as two implementations of the same boundary does.

Code from the project

Reviewed source: `README.md`


Python                         C#
pytest fixture                 [SetUp] / [TearDown]
Desktop(backend="uia")        UIA3Automation
find_editor()                  FindEditor()
pyperclip                      WinForms Clipboard
assert                         Assert.That()
allure-pytest                  Allure.NUnit

Detailed explanation

The concrete APIs differ, but both stacks perform the same responsibilities: test lifecycle, UIA client creation, window/control discovery, deterministic input, observable waits, assertions, evidence capture and cleanup. The repository is valuable because you can compare each responsibility side-by-side against the same application behavior.

Initially, two apparently different test frameworks. Once this step completes, one conceptual architecture with language/library-specific implementations.

Design reasoning

If you compare only syntax, you miss architectural differences such as STA clipboard handling in C# and pytest's yield-based teardown in Python.

Key points

  • Responsibilities transfer across languages.
  • Implementation details still matter at OS boundaries.

Common pitfalls

  • Concluding that two APIs are equivalent merely because their test scenarios look similar.

Source registry

10 chapter references
Desktop Automation Lab — reviewed commit

Exact source code used by every project-walkthrough lesson

sergiiiavt · Reference implementation
Source ↗
UI Automation Overview

Windows UI Automation tree, elements, control types, properties and patterns

Microsoft Learn · Official documentation
Source ↗
pywinauto documentation

Python Windows GUI automation, UIA backend and wrappers

pywinauto · Official documentation
Source ↗
pytest fixtures reference

Fixture injection, yield values and teardown semantics

pytest · Official documentation
Source ↗
FlaUI

FlaUI architecture, UIA2/UIA3 backends and Windows automation elements

FlaUI · Official repository
Source ↗
NUnit SetUp and TearDown

Per-test setup/teardown lifecycle and inheritance behavior

NUnit · Official documentation
Source ↗
Workflow syntax for GitHub Actions

Triggers, jobs, runners, steps, actions and conditions

GitHub Docs · Official documentation
Source ↗
Contexts reference

github, runner, secrets and variables contexts used by the CI workflow

GitHub Docs · Official documentation
Source ↗
Allure Report — Pytest

pytest result generation, attachments and Allure report workflow

Allure Report · Official documentation
Source ↗
Allure Report — NUnit

NUnit integration, result directory, metadata and attachments

Allure Report · Official documentation
Source ↗