MSBA-359 · Lesson 7 of 12 · 21 min

Domain review: testing and deployment

▶ Video coming soon A video version of this lesson is on the way.

Joss's first test codeunit, written in October for the CF Roastery app, failed for a reason that had nothing to do with his code: the procedure showed a confirmation dialog, and the test runner had no one to click Yes. Noor had let him find that out on his own. "You will never forget handler functions now," she said, "and that is one exam question you will get right without thinking." This lesson collects the rest of the testing, monitoring and deployment material in the same spirit: the facts that make the difference between code that works on your machine and code that keeps working at a customer's site.

The lesson covers Test and monitor AL code (10 to 15 percent), with its two groups on tests and telemetry, and the deployment and maintenance bullets of the install, develop and deploy area, including install and upgrade code from the codeunits group.

Testing in Business Central

Automated tests in Business Central are AL code. A test codeunit has Subtype = Test, and each procedure with the [Test] attribute is a test method that passes if it completes without an error and fails if any error is raised. Tests usually follow a Given, When, Then shape: create the data, run the code, assert the result. They live in a separate test app with its own ID range and a dependency on the app under test, so test code never ships to production.

Microsoft ships its test framework as the Test Toolkit: the Test Runner app that runs tests and records results, Library Assert with methods such as AreEqual, IsTrue, RecordIsEmpty and ExpectedError, the Any app for repeatable random values, Library Variable Storage for passing values between tests and handlers, and larger libraries of helper codeunits such as Library - Sales. Microsoft's own tests for the base application are available too, and running the relevant standard tests after a change is the quickest way to find out whether an extension broke standard behaviour.

A test codeunit with a pure calculation test and a test that answers a confirmation dialog through a handler (second body abbreviated).
codeunit 50910 "CNF Warranty End Date Tests"
{
    Subtype = Test;
    TestPermissions = Disabled;

    var
        Assert: Codeunit "Library Assert";

    [Test]
    procedure EndDateIsDayBeforeAnniversary()
    var
        Mgt: Codeunit "CNF Warranty Mgt.";
        StartDate: Date;
        Period: DateFormula;
    begin
        // [GIVEN] a 24-month warranty starting January 15, 2027
        StartDate := DMY2Date(15, 1, 2027);
        Evaluate(Period, '<24M>');
        // [WHEN] the end date is calculated
        // [THEN] it is January 14, 2029
        Assert.AreEqual(DMY2Date(14, 1, 2029), Mgt.CalcEndDate(StartDate, Period), 'End date must be the day before the anniversary');
    end;

    [Test]
    [HandlerFunctions('ConfirmVoidYes')]
    procedure VoidingAskForConfirmation()
    begin
        // [GIVEN] an active registration; [WHEN] it is voided; [THEN] the status is Void
    end;

    [ConfirmHandler]
    procedure ConfirmVoidYes(Question: Text[1024]; var Reply: Boolean)
    begin
        Reply := true;
    end;
}

Handler functions answer user interface calls that would otherwise stop a test. A test lists them in [HandlerFunctions], and each is a procedure with an attribute such as [ConfirmHandler], [MessageHandler], [ModalPageHandler], [PageHandler], [StrMenuHandler], [RequestPageHandler], [ReportHandler] or [SendNotificationHandler]. If code raises UI that no handler covers, the test fails; if a listed handler is never called, the test also fails, which catches tests that no longer exercise what they claim to. TestPage variables open pages in test mode so a test can set fields and invoke actions as a user would, and TestRequestPage does the same for report request pages.

Two properties control the environment of a test. TestPermissions on a test codeunit decides whether tests run with restricted permissions or with the test runner's full rights; testing with realistic permissions catches the kind of failure Dovrin hit when Joss had tested only as a super user. TestIsolation on a test runner codeunit decides whether database changes are rolled back after each codeunit or each test function. A test method's TransactionModel attribute (AutoRollback, AutoCommit or None) controls commits within the test.

Running tests

The outline speaks of semiautomated testing and of running standard tests, and both happen in the client. The AL Test Tool page lets a developer or tester pick test codeunits, run them, and see which methods passed or failed with their error messages. In a container, the toolkit is imported with one command of Microsoft's container tooling, and pipelines such as AL-Go for GitHub import it automatically and run every test on every pull request. In an online sandbox, tests can be run for verification, within limits Microsoft sets to protect the service; long or heavy test runs belong in containers. Tests are not allowed in production environments at all, because they create and change data.

Telemetry

Business Central sends telemetry to Azure Application Insights. There are two independent destinations. Environment telemetry is configured in the Business Central admin center with an Application Insights connection string on the environment, and receives signals from everything in that environment. App telemetry is configured in an extension's app.json with applicationInsightsConnectionString, and receives signals about that app from every environment where it is installed. A customer usually owns the first; a publisher owns the second.

Common telemetry signals by event ID.
Event IDSignalTypical question
RT0005Long-running SQL queryWhich database call is slow, and from which AL code?
RT0018Long-running AL methodWhich procedure is slow?
RT0012Database lock timed outWhy did a job fail with a lock message?
RT0008Incoming web service callWhich API calls fail or take long?
RT0019Outgoing web service callIs the external service slow or failing?
RT0030Error dialog shownWhich errors do users see?
LC0010 to LC0023Extension lifecycle eventsDid an install, update or compilation fail?

Signals land mostly in the traces table, each with custom dimensions such as the event ID, environment, company, extension and duration. They are queried with Kusto Query Language (KQL) in Application Insights, in Microsoft's Power BI telemetry apps, or in troubleshooting notebooks built on the same data. You do not need to write complex KQL for MB-820, but you should be able to read a short query and say what it returns.

A KQL query counting lock timeouts per AL object per hour over the last day.
traces
| where timestamp > ago(1d)
| where customDimensions.eventId == "RT0012"
| summarize timeouts = count() by tostring(customDimensions.alObjectName), bin(timestamp, 1h)
| order by timeouts desc

Extensions add their own signals with Session.LogMessage, passing an event ID, a message, a Verbosity, a DataClassification, a TelemetryScope and a dictionary of custom dimensions. TelemetryScope::ExtensionPublisher sends the signal only to the app's own resource; TelemetryScope::All sends it to the environment's resource as well. Only signals classified as SystemMetadata are emitted, so customer data never leaves through telemetry by accident. The Feature Telemetry codeunit in the System Application offers consistent methods for logging feature use, setup and errors. Custom event IDs should carry a short prefix unique to the app.

Install and upgrade code

An install codeunit (Subtype = Install) runs once when an extension is installed, with OnInstallAppPerDatabase and OnInstallAppPerCompany. It typically creates setup records with defaults and registers Copilot capabilities or assisted setup. An upgrade codeunit (Subtype = Upgrade) runs when a newer version replaces an older one, with six triggers in a fixed order.

A sequence of six boxes in two rows. Per database and per company check preconditions, then per database and per company upgrade, then per database and per company validate. A note says any error stops the upgrade and the old version remains.
The order of upgrade codeunit triggers.

The triggers run in this order: OnCheckPreconditionsPerDatabase, OnCheckPreconditionsPerCompany, OnUpgradePerDatabase, OnUpgradePerCompany, OnValidateUpgradePerDatabase and OnValidateUpgradePerCompany. The per-company triggers run once for each company. If any trigger raises an error, the upgrade fails and the previous version stays in place. Upgrade code must be safe to run more than once, because an upgrade can be retried, and it must run only once per change. The Upgrade Tag module gives both: before upgrading, check HasUpgradeTag for a tag that names the change; after upgrading, call SetUpgradeTag; and register the tag through the per-company or per-database tag events so new installations are marked as already upgraded. The DataTransfer data type copies field values between tables or fields in bulk, set-based, which is much faster than a loop for large tables.

An upgrade codeunit guarded by an upgrade tag, in the style of the CF Roastery v1.3 change in MSBA-353 (tag registration omitted).
codeunit 50150 "CFR Upgrade"
{
    Subtype = Upgrade;

    trigger OnUpgradePerCompany()
    var
        UpgradeTag: Codeunit "Upgrade Tag";
    begin
        if UpgradeTag.HasUpgradeTag(ParcelTableTag()) then
            exit;
        MoveTrackingToParcels();
        UpgradeTag.SetUpgradeTag(ParcelTableTag());
    end;

    local procedure ParcelTableTag(): Code[250]
    begin
        exit('CFR-1.3-PARCEL-TABLE-20261102');
    end;

    local procedure MoveTrackingToParcels()
    begin
        // DataTransfer from the old tracking field to the new parcel table
    end;
}

Deploying extensions

Lesson 3 covered how an extension reaches production: Extension Management, the admin center, or a pipeline, never Visual Studio Code. A few more deployment facts are worth knowing. When uploading a per-tenant extension through Extension Management, the administrator chooses whether it is deployed to the current version, or with the next minor or next major update, which lets a partner prepare a version compiled for the coming release. A per-tenant extension with the same app ID as a Marketplace app cannot be installed beside it. Breaking schema changes, such as removing a field, are refused on synchronization unless done through obsoletion: mark the field ObsoleteState = Pending in one version, move its data, and set it to Removed in a later one.

AL-Go for GitHub is Microsoft's open-source set of templates and workflows for Business Central projects, with one template for per-tenant extensions and one for Marketplace apps. It builds the apps in a container or with the newer build tools, runs tests, runs code analysis, produces signed artifacts, and deploys to environments defined as GitHub environments, with approvals for production if configured. Corbel & Finch's CF Roastery repository has used it since October 2026, with two approvals required for PROD. Azure DevOps pipelines are an alternative; the exam cares about the concepts (source control, build, test, deploy, approvals) more than any one tool.

A left-to-right pipeline. A pull request triggers a build that compiles with code analysis and runs tests in a container. A merged change produces an artifact deployed to a sandbox for review, then, after approvals, to production. Telemetry from production flows back to the developers.
A typical source-to-production pipeline for a per-tenant extension, with telemetry closing the loop.

Maintaining extensions after go-live

Maintenance is where testing, telemetry and deployment meet. Each release is a new version number. Each data change has upgrade code guarded by a tag. Each removed element passes through obsolete pending first. Each major Business Central release is rehearsed in a sandbox on the preview version, with the test app run against it. And telemetry from production tells you what broke, what is slow and what is not used. Noor's rule for Joss was that no Quarrystone app ships without three things: tests that run in the pipeline, an app telemetry connection string, and upgrade code for every schema change since the last version.

Performance as part of monitoring

Telemetry finds slow code; the developer then has to make it faster. The performance profiler in the client records a session and shows where time is spent by method and object, which confirms what RT0005 and RT0018 signals suggest. The usual remedies are routine. Read only the fields you need with SetLoadFields. Calculate FlowFields with SetAutoCalcFields before a loop instead of CalcFields inside it. Replace loops with CalcSums, ModifyAll, DeleteAll or a query where the logic allows. Filter on fields covered by a key, and add keys for frequent filters while remembering that each extra key slows inserts. Move heavy calculation for page parts into page background tasks, so the page opens at once and the values arrive a moment later. Move batch work into the job queue, scheduled away from busy hours and from other jobs that lock the same tables.

Testing Copilot features and upgrades

Two kinds of code are hard to test with ordinary assertions. Copilot features call a model whose output varies. The deterministic parts, such as building the prompt, parsing the JSON answer and validating proposals against real records, are tested with ordinary test codeunits that simulate the model's answer with fixed text, as the café transfer tests did in MSBA-353. The model's behaviour itself is evaluated with the Test Toolkit's support for AI tests, which run a dataset of inputs through the feature and check the outputs, so that a changed prompt or model version can be compared with the last run.

Upgrade code runs once in real life, which makes it easy to forget. An upgrade test installs the old version, creates data in the old shape, upgrades to the new version and checks that the data arrived in the new shape. AL-Go for GitHub can run such tests in its pipeline. For a per-tenant extension with one customer, a manual rehearsal in a sandbox copied from production, before the real deployment, is the minimum.

Choosing what to test

No team tests everything, so tests go where failure is expensive. Noor's order of priority for Joss was: anything that posts or changes money or stock; anything with branching logic such as date calculations and validations; integration code that parses external data; upgrade code; and finally user interface flows, which are the slowest to test and the most likely to change. A test is worth writing when a bug in that code would reach a customer before anyone noticed. A test is also worth writing for every bug fixed, so that the same bug cannot quietly return in a later version.

Worked problem

The failing nightly job

After a new version of an extension is deployed, a nightly job queue entry that imports web shop orders starts failing two nights in five with a lock message, and users report that one page has become slow. How does a developer investigate and prevent a repeat?

Show solution
  1. Query environment telemetry for RT0012 lock timeouts and job queue error events at the failure times, and RT0018 and RT0005 for the slow page.
  2. Identify the competing job or process holding locks, and reschedule or shorten one; for the page, look at the slow method and the SQL it runs.
  3. Fix the code, write a test that reproduces the defect, and add a custom telemetry event with timing for the import.
  4. Ship the fix through the pipeline so tests and analysis run before deployment.

Answer: Telemetry finds the cause; a test proves the fix and prevents regression; custom signals and the pipeline make the next problem visible earlier.

Common mistakes

  • MistakeWriting a test for code that shows a dialog without a handler.

    InsteadAdd the right handler function and list it in HandlerFunctions.

  • MistakeRunning tests in production to check a fix.

    InsteadTests are not allowed in production; run them in containers or sandboxes.

  • MistakeLogging customer data in custom telemetry.

    InsteadOnly SystemMetadata signals are emitted; keep customer data out of messages.

  • MistakeWriting upgrade code without an upgrade tag.

    InsteadCheck and set a tag so the code runs once and is safe to retry.

  • MistakeRemoving a field in one release.

    InsteadMark it obsolete pending, migrate data, then remove it later.

Summary and key terms

  • Test codeunits use Subtype = Test and [Test] methods; tests live in a separate app with the Test Toolkit libraries.
  • Handlers answer UI calls; TestPermissions and TestIsolation control the test environment; the AL Test Tool runs tests in the client.
  • Environment telemetry is set in the admin center; app telemetry in app.json; KQL queries the traces table by event ID.
  • Session.LogMessage adds custom signals; TelemetryScope decides who receives them; only SystemMetadata is emitted.
  • Upgrade triggers run check, upgrade, validate, each per database then per company; upgrade tags make code run once.
  • AL-Go for GitHub builds, tests and deploys with approvals; schema removals go through obsoletion.
Test Toolkit
Microsoft's set of test apps, including Test Runner, Library Assert and Any.
Handler function
A test procedure that answers a confirm, message, page or report call during a test.
TestPermissions
A test codeunit property that controls the permissions tests run with.
Application Insights
The Azure monitoring service that receives Business Central telemetry.
TelemetryScope
A LogMessage parameter: ExtensionPublisher or All.
Upgrade tag
A named marker recording that a specific upgrade step has run.
AL-Go for GitHub
Microsoft's templates and workflows for building, testing and deploying Business Central apps.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Which attribute lists the handlers a test needs?

    Show answer

    HandlerFunctions.

  2. Where is environment telemetry configured?

    Show answer

    In the Business Central admin center, on the environment.

  3. Which upgrade trigger runs first?

    Show answer

    OnCheckPreconditionsPerDatabase.

  4. Which data type copies values between tables in bulk during upgrades?

    Show answer

    DataTransfer.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz