MSBA-353 · Lesson 5 of 12 · 21 min

Automated tests

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

In mid-October, Noor changed one line in the café transfer validation so that quantities would round to whole bags. The change worked for bags and quietly broke merchandise, where the café SKUs count mugs in pieces and the rounding ran before the unit conversion. Nobody noticed for two days, until Callum tried a draft with mugs in CONFIG. "That is the last bug I want you to find by hand," Noor said, and the next session was about automated tests. Business Central has a mature test framework, used by Microsoft for tens of thousands of tests on the base application, and the MB-820 outline asks candidates to test applications, install and run the Test Toolkit, and develop test codeunits and procedures.

Why test automatically

An extension at Corbel & Finch touches posting, inventory and money. Manual testing catches the obvious, but it is slow, it is skipped when deadlines loom, and it never covers every case after every change. Automated tests are AL code that sets up data, runs the feature and checks the result, and they run in minutes on every change. They also document intent: a test called DraftDropsVariantNotStockedAtCafe says what the code must do more clearly than a comment. And they are what makes the pipeline in lesson 8 safe: a pull request that breaks a test cannot be merged.

Kinds of automated test in an extension.
LevelWhat it checksExample at Corbel & Finch
Unit testOne procedure with controlled inputsThe rate parser returns the lowest price from sample JSON
Integration testSeveral objects together, with real postingPosting a web shop order through the API codeunit creates the expected ledger entries
UI testPages and actions through test pagesChoosing Get Rate on a sales order fills the shipping charge field
Upgrade testData after an upgrade codeunit runsTracking numbers move from the old field to the new table
Performance testSpeed under loadTwenty users drafting transfers at once (lesson 7)

The Test Toolkit

Microsoft ships the test framework as a set of apps, together called the Test Toolkit. The core pieces are the Test Runner app, which runs tests and records results; the Library Assert app, with methods such as AreEqual, IsTrue and ExpectedError; the Any app, which generates repeatable pseudo-random values; and Library Variable Storage, which passes values between a test and its handlers. Larger libraries, such as the system application test library and the base application test libraries with codeunits like Library - Sales, Library - Inventory and Library - Warehouse, create realistic data in a line or two. Microsoft's own test apps, with the tests for the base application, are also available to run.

The toolkit is installed where tests run. In a container created with Microsoft's tooling, a single command imports the toolkit, and AL-Go for GitHub does it automatically in each build. In an online sandbox, tests can be run for manual verification, but Microsoft does not allow large test runs or tests that take more than 15 minutes per method, and recommends against running tests for more than an hour or two a day. Tests are not allowed in production environments at all, because they might change business data or call external systems. The container is the recommended home for large runs and pipeline gates.

Two app boxes. The main app CF Roastery contains tables, pages, codeunits and API pages. The test app CF Roastery Tests contains test codeunits and depends on the main app and on the Test Toolkit apps: Test Runner, Library Assert, Any, Library Variable Storage and the test libraries. An arrow shows that only the main app is deployed to production; the test app goes only to containers and sandboxes.
The test app depends on the main app and the Test Toolkit; only the main app reaches production.

A separate test app

Tests live in their own app, not inside the main extension. The test app's app.json declares a dependency on the main app and on the toolkit apps it uses, and it uses its own object ID range. Keeping them apart means the main app never carries test code into production, and test libraries are never a dependency of production code. Noor created a folder CF Roastery Tests next to the main app in the same workspace, with the dependencies listed in its manifest.

A test app manifest that depends on the main app and toolkit apps. The IDs shown are placeholders; copy the real app IDs from each app's own manifest.
{
  "id": "6f1c2b40-0d1a-4b8e-9a7e-2f5b1c3d4e51",
  "name": "CF Roastery Tests",
  "publisher": "Quarrystone Business Systems",
  "version": "1.3.0.0",
  "dependencies": [
    { "id": "b9a4e7d2-5c61-4f0a-8e3b-1d2c3b4a5f60", "name": "CF Roastery", "publisher": "Quarrystone Business Systems", "version": "1.3.0.0" },
    { "id": "dd0be2ea-f733-4d65-bb34-a28f4624fb14", "name": "Library Assert", "publisher": "Microsoft", "version": "29.0.0.0" },
    { "id": "e7320ebb-08b3-4406-b1ec-b4927d3e280b", "name": "Any", "publisher": "Microsoft", "version": "29.0.0.0" }
  ],
  "idRanges": [ { "from": 50900, "to": 50999 } ],
  "application": "29.0.0.0"
}

Test codeunits and test methods

A test codeunit has Subtype = Test. Each procedure marked with the [Test] attribute is a test method; it passes if it finishes without error and fails if any error is raised. Other procedures in the codeunit are helpers or handlers. A good test reads in three parts, often marked with comments: Given some starting data, When the code under test runs, Then the result is checked with assertions.

Two tests for the validation codeunit, including one that would have caught the October rounding bug.
codeunit 50910 "CFR Transfer Draft Tests"
{
    Subtype = Test;
    TestPermissions = Disabled;

    var
        Assert: Codeunit "Library Assert";
        Any: Codeunit Any;
        IsInitialized: Boolean;

    [Test]
    procedure DraftDropsVariantNotStockedAtCafe()
    var
        Validator: Codeunit "CFR Transfer Draft Validator";
        TempLine: Record "CFR Transfer Draft Line" temporary;
        Dropped: List of [Text];
    begin
        // [GIVEN] CAFE2 stocks Foghorn only as ESPRESSO, max 6, 2 on hand
        Initialize();
        CreateCafeSku('CAFE2', 'FC-FOG', 'ESPRESSO', 6, 2);

        // [WHEN] the model proposes the DECAF variant
        Validator.Validate('CAFE2', '{"lines":[{"itemNo":"FC-FOG","variant":"DECAF","quantity":2,"unit":"CASE"}],"unmatched":[]}', TempLine, Dropped);

        // [THEN] no line is proposed and the drop is explained
        Assert.RecordIsEmpty(TempLine);
        Assert.AreEqual(1, Dropped.Count(), 'One line should be reported as dropped');
    end;

    [Test]
    procedure MerchandiseQuantityIsNotRoundedToBags()
    var
        Validator: Codeunit "CFR Transfer Draft Validator";
        TempLine: Record "CFR Transfer Draft Line" temporary;
        Dropped: List of [Text];
    begin
        // [GIVEN] CAFE1 stocks black mugs in pieces, max 24, 5 on hand
        Initialize();
        CreateCafeSku('CAFE1', 'MR-MUG-BLK', '', 24, 5);

        // [WHEN] the model proposes 19 pieces
        Validator.Validate('CAFE1', '{"lines":[{"itemNo":"MR-MUG-BLK","variant":"","quantity":19,"unit":"PCS"}],"unmatched":[]}', TempLine, Dropped);

        // [THEN] the quantity stays 19 pieces
        TempLine.FindFirst();
        Assert.AreEqual(19, TempLine.Quantity, 'Merchandise must keep its piece quantity');
        Assert.AreEqual('PCS', TempLine."Unit of Measure Code", 'Unit must stay PCS');
    end;
}

Look at what the tests do not do: they do not call Azure OpenAI. The model's output is simulated with a fixed JSON string, so the tests check the deterministic AL logic, which is where bugs like the rounding one live, and run in milliseconds without cost. The second test was written first, failed against the buggy code, and passed after the fix. That order, a failing test, then the fix, then a passing test, is the habit Noor wanted Callum to see.

Initialize and test data

Most test codeunits have an Initialize procedure that each test calls first. It resets anything that a test might have changed, and, guarded by an IsInitialized flag, creates shared setup only once per codeunit run. Data that matters to the test is created explicitly in the Given part; data that does not matter, such as a customer name, comes from Any or the libraries with random values, so the test does not depend on demo data that might change between versions.

By default, the test runner isolates tests so that each one starts clean. Test isolation is a property of the test runner codeunit: with isolation per codeunit or per function, changes a test makes to the database are rolled back afterward. A test method can also set a TransactionModel attribute: AutoRollback rolls back at the end and fails if the code commits, AutoCommit lets the code commit as it would in production, and None behaves like a real client session. Posting routines commit, so integration tests that post documents usually run with AutoCommit inside an isolated runner.

Handlers for user interface

Code that shows a confirm dialog, a message or a page would stop an unattended test, waiting for a click that never comes. Handler methods answer those calls instead. A test lists the handlers it expects in a [HandlerFunctions] attribute, and each handler is a procedure with an attribute such as [ConfirmHandler], [MessageHandler], [ModalPageHandler], [PageHandler], [StrMenuHandler], [RequestPageHandler] or [SendNotificationHandler]. If the code shows UI that no handler covers, the test fails; if a listed handler is never called, the test also fails, which catches code that silently stopped asking a question it should ask.

A UI test with a test page and two handlers.
[Test]
[HandlerFunctions('ConfirmYesHandler,RateMessageHandler')]
procedure GetRateFillsShippingCharge()
var
    SalesOrder: TestPage "Sales Order";
begin
    // [GIVEN] a wholesale order with three cases and a stubbed rate of 18.40
    Initialize();
    LibraryVariableStorage.Enqueue(18.40);
    OpenNewWholesaleOrder(SalesOrder, 'FC-BRK', 3);

    // [WHEN] the user chooses Get Rate and confirms
    SalesOrder.CFRGetRate.Invoke();

    // [THEN] the shipping charge field shows the rate
    SalesOrder.CFRShippingCharge.AssertEquals(18.40);
end;

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

[MessageHandler]
procedure RateMessageHandler(Message: Text[1024])
begin
end;

A TestPage variable opens any page in test mode, so the test can set fields, invoke actions and assert values exactly as a user would, without a browser. TestRequestPage does the same for report request pages. UI tests are slower and more brittle than unit tests, so Noor wrote only a few, for the actions users depend on most.

Testing outbound calls

The Get Rate test above must not call Tidewell. Noor's rate client hides the HTTP call behind an interface, an AL object type covered in MSBA-352: the production implementation calls the carrier, and the test injects a stub implementation that returns the value queued in Library Variable Storage. Recent versions of AL also let test codeunits intercept HttpClient requests with a handler method, returning a prepared response for each request, which tests the real client code without leaving the test. Either way, tests never depend on an external service being up, and they can simulate failures, such as a 503 response, that are hard to provoke on demand.

Worked problem

Choosing tests for the web shop order import

The import codeunit reads a JSON order, finds the WEB customer, creates a sales order with lines, applies the S-LIST-2027 prices and releases it. Which tests should Noor write first?

Show solution
  1. Happy path: a valid order with two items creates one released order with two lines at list prices. Integration test with AutoCommit.
  2. Unknown item: an order with an item number that does not exist fails with a clear error and creates nothing.
  3. Duplicate: importing the same web shop order number twice creates only one sales order.
  4. Blocked item: an order line for a blocked coffee fails with the item named in the error.
  5. Parsing: malformed JSON produces a clear error rather than a runtime exception.

Answer: Start with one happy-path integration test and a handful of negative tests for the errors most likely in production: unknown items, duplicates, blocked items and bad input.

Running tests

Tests run in several ways. The AL Test Tool page in the client lists test codeunits and methods, runs them and shows results, which suits a quick check in a sandbox. Visual Studio Code can publish the test app and run tests in a container or sandbox, and community extensions and recent AL tooling integrate the results into the editor. In pipelines, AL-Go runs every test app in a container on every build and publishes the results with the build, as lesson 8 shows. Code coverage can be collected during a run, showing which lines of the main app the tests actually executed.

TestPermissions on a test codeunit controls permission checking during tests. Disabled runs without permission checks, the usual setting for logic tests. Restrictive and NonRestrictive run tests with the permission sets the test assigns, so a test can prove that a user with only CF-CAFE permissions can draft and create a café transfer, and that one without them gets a permission error. Those permission tests catch the classic go-live failure: a feature that works for the developer with SUPER and fails for the café manager. The warranty extension in MSBA-352 met exactly that defect when Dovrin's first posting failed on permissions after testing as SUPER, and Noor did not want to see it twice.

Testing Copilot features

The model call itself needs a different kind of test. The Business Central Test Toolkit includes capabilities for testing AI features: developers write AL tests that read datasets of prompts, such as fifty realistic café requests and a dozen adversarial ones, run the real feature, and check the outputs with automated rules, such as "no line for an item not stocked at the café" and "no quantity above maximum unless extra was requested". Because model answers vary, these tests report pass rates rather than a single pass or fail. Noor ran the dataset before each prompt change and kept the results, so that a change that made answers worse would show up as a lower pass rate before it reached users.

What to test first

A team new to automated testing cannot cover everything at once, and should not try. Noor used three questions to decide where the first tests went. Where would a bug cost money or stock? Posting, pricing and quantity calculations come first. Where has a bug already happened? The rounding bug got a test the same day, and every later bug did too, so it can never return quietly. Where will the code change most? The Tidewell client and the Copilot validation were still evolving, so tests there would pay back fastest. Setup pages and simple lookups came last.

Where CF Roastery's first tests went.
AreaTests by mid-NovemberReason
Café transfer validation14 unit testsQuantities and items reach real transfer orders
Web shop order import6 integration testsCreates sales orders and posts nightly
Tidewell rate and booking9 unit tests with stubsExternal dependency, many failure modes
Intake checks and quarantine5 tests, 2 with permissionsUsed by warehouse staff with limited permissions
Parcel upgrade2 upgrade testsRuns once per environment and must be right

Keeping tests trustworthy

A test suite is only useful while people believe it. Tests that fail randomly, often because they depend on the date, on demo data or on the order in which they run, teach developers to ignore red builds. Noor's rules were that every test creates its own data, uses fixed dates through the work date or explicit parameters rather than today's date, never depends on another test having run, and fails with a message that says what was expected. When a test fails in the pipeline, the first question is whether the code or the test is wrong, and the answer goes into the pull request. Deleting a failing test to get a build through is treated like deleting an alarm because it was noisy.

Tests also need maintenance when the product changes. When Microsoft changes a base application procedure that a test library depends on, the Test Next Major workflow in lesson 8 shows the failure weeks before the update, and the test is adjusted then rather than in a rush.

Common mistakes

  • MistakePutting test codeunits in the main app.

    InsteadKeep tests in a separate test app that depends on the main app.

  • MistakeRunning test suites in production.

    InsteadRun tests in containers or, for small manual checks, sandboxes; production does not allow tests.

  • MistakeRelying on demo data that might change.

    InsteadCreate the data each test needs, using libraries and Any for the rest.

  • MistakeTesting only as a user with SUPER.

    InsteadUse TestPermissions and permission sets to test as real roles.

  • MistakeCalling the real model or carrier in unit tests.

    InsteadStub external calls with interfaces or HTTP handlers and test the AL logic.

Summary and key terms

  • The Test Toolkit includes Test Runner, Library Assert, Any, Library Variable Storage and test libraries.
  • Tests live in a separate test app; production environments do not allow tests, and containers suit large runs.
  • Test codeunits use Subtype = Test and [Test] methods written as Given, When, Then.
  • Handlers answer confirm, message and page calls; unused or missing handlers fail the test.
  • TransactionModel and test isolation control rollback; TestPermissions controls permission checks.
  • Copilot features are tested with datasets and pass rates, while the deterministic AL logic gets ordinary tests.
Test codeunit
A codeunit with Subtype = Test that contains test methods.
Test runner
A codeunit with Subtype = TestRunner that runs tests and controls isolation.
Handler method
A test procedure that responds to UI calls such as confirms and messages.
TestPage
A variable type that opens a page in test mode to set fields and invoke actions.
Library Assert
The toolkit codeunit with assertion methods such as AreEqual and ExpectedError.
Any
The toolkit codeunit that generates repeatable pseudo-random test values.
TransactionModel
A test attribute that sets whether a test rolls back, commits or behaves like a client.

Practice problems

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

  1. Why does the transfer draft test pass a fixed JSON string instead of calling Azure OpenAI?

    Show answer

    To test the deterministic validation logic quickly, repeatably and without cost or dependence on the model.

  2. A test lists ConfirmYesHandler, but the code no longer asks for confirmation. What happens?

    Show answer

    The test fails because a listed handler was not called.

  3. Where should the pipeline run the full test suite?

    Show answer

    In a container, not in an online sandbox or production.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz