UI Testing with Test Pages
Earn 25 points (50 with Pro) in two steps
- ① Read through the lesson — each section gets a ✓ as you scroll through it.
- ② When every section has a ✓, tap Complete lesson.
0 of 12 read · keep scrolling
✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro
Advanced Testing: UI Testing with Test Pages in AL
Introduction: Why UI Testing Matters
In the world of Business Central development, the AL (Application Language) environment provides a rich set of tools for building complex business logic. However, logic that works perfectly in isolation often fails when it encounters the complexities of the user interface. UI testing—specifically using Test Pages—allows you to simulate how an actual user interacts with your application. By automating these interactions, you ensure that your pages, actions, and field validations behave correctly under various conditions.
Testing at the UI level is fundamentally different from unit testing your code units. While unit tests check the math and the data processing, UI tests check the "experience." If a user clicks a button, does the correct sub-page open? If a user enters a value into a field, does the field validation trigger the expected side effects? These are the questions that Test Pages answer. Mastering this skill is critical for any developer who wants to move beyond simple code verification and start delivering reliable, user-ready business solutions.
Not read yet
Understanding Test Pages in AL
Test Pages are a special type of AL object designed specifically for automated testing. They act as a proxy for the actual pages in your application. When you write a test that uses a Test Page, the testing framework renders the page in a headless environment. This means the page is "loaded" into memory, allowing your code to manipulate it, read its values, and trigger its actions, just as a human would, but at machine speed.
Unlike traditional unit testing where you might instantiate a codeunit and call a function, a Test Page test requires you to bind the test object to the page object. Once bound, you gain access to the controls of that page. You can set values in fields, trigger actions, and verify that the page state changes as expected. This creates a bridge between your business logic and the visual layer of your product.
Callout: Unit Testing vs. UI Testing Unit testing is about verifying the logic within a single function or codeunit. It is fast, isolated, and does not involve the database or the UI. UI testing with Test Pages is about verifying the interaction between the user and the application. It involves the page object, field triggers, and action execution, making it a higher-level check that ensures the "plumbing" of your user interface is connected correctly.
Not read yet
Setting Up Your Test Project
Before you can write your first Test Page test, you need to ensure your environment is configured for testing. Your workspace should contain both your main application and a dedicated test project. The test project must have a dependency on the main application and should include the "Test Runner" framework components provided by Microsoft.
- Create a new AL project specifically for your tests.
- In the
app.jsonfile of your test project, add your main application as a dependency. - Ensure the
testproperty is enabled in yourlaunch.jsonconfiguration if you are running tests directly from VS Code. - Create a new file with the suffix
.aland set theSubtypeof your object toTest.
Once your project is structured correctly, you are ready to start writing your first test case. Remember that keeping your tests organized is just as important as writing them. Group your tests by functionality or page name to make it easier to maintain the suite as your application grows in complexity.
Not read yet
The Anatomy of a Test Page Interaction
When you work with Test Pages, you will primarily interact with the TestPage data type. This type provides methods to open, close, filter, and navigate pages. Let’s look at a basic example where we want to test that a Customer Card page opens correctly and displays the expected data.
Example: Testing a Page Opening
[Test]
procedure TestCustomerCardOpening()
var
CustomerCard: TestPage "Customer Card";
Customer: Record Customer;
begin
// Create a dummy customer for the test
Customer.Init();
Customer."No." := 'TEST-001';
Customer.Name := 'Test Customer';
Customer.Insert();
// Open the test page
CustomerCard.OpenEdit();
CustomerCard.GotoRecord(Customer);
// Verify the field values
CustomerCard.Name.AssertEquals('Test Customer');
// Close the page
CustomerCard.Close();
end;
In this example, the CustomerCard variable acts as our handle to the UI. We use OpenEdit() to simulate opening the page in edit mode. The GotoRecord() method is vital—it tells the Test Page which specific record from the database it should be displaying. Finally, we use AssertEquals to verify that the value displayed on the screen matches our expectations.
Note: Always ensure you clean up your test data. While the test framework often uses a sandbox environment, leaving stale records can cause "flaky" tests that pass or fail inconsistently based on what happened in the previous run.
Not read yet
Advanced Interactions: Actions and Sub-pages
The real power of Test Pages comes into play when you need to trigger actions or interact with sub-pages (parts). Many Business Central pages are complex, containing multiple sub-pages like Sales Lines or Contact lists. The TestPage object allows you to drill down into these parts using the variable name defined in the page object.
Example: Triggering an Action on a Page
Suppose you have a custom action on the Sales Order page called "Post Order." You want to ensure that clicking this button changes the status of the order.
[Test]
procedure TestPostSalesOrderAction()
var
SalesOrder: TestPage "Sales Order";
SalesHeader: Record "Sales Header";
begin
// Setup: Create a sales order
SalesHeader.Init();
SalesHeader."Document Type" := SalesHeader."Document Type"::Order;
SalesHeader.Insert();
// Open the page and navigate
SalesOrder.OpenEdit();
SalesOrder.GotoRecord(SalesHeader);
// Trigger the action
SalesOrder."Post Order".Invoke();
// Verify the result
SalesOrder.Status.AssertEquals(SalesHeader.Status::Released);
SalesOrder.Close();
end;
When you call Invoke() on an action, the test framework executes the AL code associated with that action. This is the closest you can get to a real user clicking a button. If the action triggers a dialog or a request page, you may need to handle that using the Trap method, which we will cover in the next section.
Not read yet
Handling Dialogs and Request Pages
One of the most common hurdles in UI testing is the appearance of modal dialogs or request pages. If your code calls MESSAGE, CONFIRM, or STRMENU, the test will fail if you do not "trap" the dialog. The Trap method tells the test engine: "I expect a page (or dialog) to appear, and I want to handle it."
Working with Request Pages
If you are testing a report or a process that opens a request page, you must trap the request page before you invoke the action that triggers it.
[Test]
procedure TestReportRequestPage()
var
SalesOrder: TestPage "Sales Order";
ReportRequestPage: TestPage "My Custom Report";
begin
SalesOrder.OpenEdit();
// Trap the request page before triggering the action
ReportRequestPage.Trap();
SalesOrder."Print Report".Invoke();
// Now interact with the request page
ReportRequestPage."Include VAT".SetValue(true);
ReportRequestPage.OK().Invoke();
SalesOrder.Close();
end;
This pattern is essential for any test that involves complex workflows. By trapping the request page, you can simulate user input, such as toggling checkboxes or selecting dates, ensuring that your report filters are applied correctly before the processing logic runs.
Callout: The Power of Trapping The
Trapmethod is not just for request pages; it works for any page that is opened as a result of an action. This includes lookups, error dialogs, and confirmation prompts. If you forget to trap a page, the test will throw an error because the test runner is waiting for the page to be handled, but the UI thread is blocked.
Not read yet
Best Practices for Robust UI Tests
Writing UI tests is an investment. If they are poorly written, they become "brittle"—meaning they break every time you make a minor change to the UI, even if the logic is still sound. Follow these practices to keep your tests stable and maintainable.
1. Keep Tests Atomic
Each test should be independent. Do not rely on the state left behind by a previous test. If you need a specific set of data, create it within the test function or use a [TestSetup] function to prepare the environment.
2. Focus on User Behavior
Don't test every single property of every control. Focus on the paths that users actually take. If a field is hidden, you don't necessarily need to test that it is hidden unless the business logic depends on that visibility. Test the "Happy Path" (the normal workflow) and the primary error paths.
3. Use Descriptive Names
Name your test functions in a way that describes the scenario and the expected outcome. For example, Test_SalesOrder_Post_StatusUpdatesToReleased is much better than Test1.
4. Avoid Hardcoding IDs
Whenever possible, use record variables to find the data you need rather than hardcoding primary keys. If your test data includes specific IDs, ensure they are generated or defined in a way that avoids collisions in multi-user environments.
5. Minimize UI Interaction
UI tests are slower than unit tests. Only use UI tests for scenarios that actually involve the UI. If you are testing a tax calculation function, do that in a unit test. If you are testing that the tax is correctly displayed on the page, use a UI test.
Not read yet
Common Pitfalls and How to Avoid Them
Even experienced developers fall into traps when writing UI tests. Here are some common mistakes and how to steer clear of them.
- The "Flaky" Test Syndrome: If a test passes sometimes and fails others, it is usually due to timing or data dependencies. Ensure that your page is fully loaded before you interact with it. Sometimes, adding a small delay or ensuring the page is focused helps, but the better approach is to rely on the test framework's built-in synchronization.
- Ignoring Error Dialogs: If your code throws an error, the test will fail. If you expect an error to be thrown (e.g., testing validation logic), use the
[HandlerFunctions]attribute to catch the error message and verify its content. - Over-Testing the UI: Don't write a test to check if a button is blue or if a field is shifted two pixels to the left. The test framework is for functional testing, not visual regression testing. Focus on whether the button works, not what it looks like.
- Failing to Close Pages: Always call
Close()on your test pages. If you don't, you might leave the test environment in a dirty state, which can impact subsequent tests running in the same session.
Not read yet
Comparison: Unit Testing vs. Test Pages
| Feature | Unit Testing | UI Testing (Test Pages) |
|---|---|---|
| Execution Speed | Very Fast | Moderate |
| Scope | Codeunits/Methods | Pages/Actions/User Workflows |
| Dependencies | Minimal | Requires Page definitions |
| Complexity | Low | High |
| Primary Use | Logic Verification | Process/Workflow Verification |
| Maintenance | Low | Moderate to High |
Step-by-Step: Testing a Complex Workflow
Let’s walk through a more complex scenario: Testing the creation of a Sales Order and ensuring the "Customer Credit Limit" warning is triggered.
- Define the Test Setup: Create a Customer with a low credit limit.
- Initialize the Test Page: Open the Sales Order page.
- Perform Interaction: Enter a Sales Order line that exceeds the credit limit.
- Trap the Warning: Use a
ConfirmHandlerto handle the credit limit warning dialog. - Verify Results: Check that the page state reflects the warning (e.g., the order is not allowed to be released).
Implementation
[Test]
[HandlerFunctions('CreditLimitConfirmHandler')]
procedure TestSalesOrderCreditLimitWarning()
var
SalesOrder: TestPage "Sales Order";
SalesHeader: Record "Sales Header";
Customer: Record Customer;
begin
// 1. Setup: Create a customer with a low credit limit
Customer.Init();
Customer."No." := 'LIMIT-CUST';
Customer."Credit Limit (LCY)" := 100;
Customer.Insert();
// 2. Open Page
SalesOrder.OpenNew();
SalesOrder."Sell-to Customer No.".SetValue(Customer."No.");
// 3. Add a line that exceeds the limit
// Note: In a real scenario, you'd drill into the subpage
SalesOrder.SalesLines.New();
SalesOrder.SalesLines.Type.SetValue(SalesOrder.SalesLines.Type::Item);
SalesOrder.SalesLines."No.".SetValue('ITEM-001');
SalesOrder.SalesLines.Quantity.SetValue(1000); // Triggers limit
// 4. Trigger release which hits the handler
SalesOrder."Release".Invoke();
// 5. Assert result
SalesOrder.Status.AssertEquals(SalesHeader.Status::Open);
end;
[ConfirmHandler]
procedure CreditLimitConfirmHandler(Question: Text[1024]; var Reply: Boolean)
begin
// We want to simulate the user clicking 'Yes'
if StrPos(Question, 'credit limit') > 0 then
Reply := true;
end;
This example shows how HandlerFunctions work. By separating the logic of handling the dialog into a dedicated function, your test code remains clean and focused on the workflow steps.
Tip: When using
HandlerFunctions, make sure the signature of your handler matches exactly what the system expects for that type of dialog (e.g.,ConfirmHandlerforCONFIRM,MessageHandlerforMESSAGE).
Not read yet
Advanced Troubleshooting
If your tests are failing, the first step is to check the Test Tool page in Business Central. It provides a detailed view of which tests failed and, more importantly, the error message returned. Often, the error will point to a specific line in your test code or a validation error triggered in the underlying table.
If the error message is vague, use the Message or Error functions within your code to debug. You can also use the AL debugger while running the test. Simply place a breakpoint in your test code or in the page code you are testing, and launch the test runner. The debugger will pause execution, allowing you to inspect variable values and the state of the page at the exact moment of failure.
Pay special attention to the Session state. UI tests run in a specific session context. If you are testing code that relies on CompanyOpen or specific user permissions, ensure that your test environment is configured to mimic the production environment as closely as possible.
Not read yet
Best Practices Checklist
- Prefix Test Objects: Use a consistent naming convention for your test objects (e.g.,
TEST_orT_) to easily distinguish them from the main application objects. - Use
AssertLibrary: Leverage theAssertcodeunit provided by Microsoft. It contains a wealth of useful functions for comparing values, checking if records exist, and handling errors. - Keep Tests Independent: Never assume that the state of the database is the same as it was in the last run. Always initialize your own data.
- Document Your Tests: Add comments to your test code explaining why a test exists. This is helpful for colleagues who might need to update the test when the business requirements change.
- Run Tests Frequently: Integrate your testing into your development workflow. Running tests locally before pushing code is the single best way to prevent bugs from reaching the production environment.
Frequently Asked Questions
Q: Can I test mobile or web-specific features? A: Test Pages are designed to test the underlying AL logic and page behavior. They do not simulate specific browser rendering engines or mobile touch gestures. They are best used for functional workflow testing.
Q: My test fails because of a missing permission. How do I fix this?
A: Ensure that the user running the test has sufficient permissions. You can also use the LibraryPermissions codeunit in your test setup to assign specific permission sets to the test user.
Q: Are Test Pages slow? A: They are slower than unit tests, but they are significantly faster than manual testing. The overhead comes from rendering the page and executing the triggers. Keep your test suite focused to maintain performance.
Q: Can I use Test Pages for external integrations? A: You can test the UI part of an integration, but for the integration itself (e.g., calling an API), you should use a mock service or a dedicated unit test to avoid hitting actual external endpoints during your test run.
Not read yet
Key Takeaways
- UI Testing is for Workflows: While unit tests verify calculations, Test Pages verify that the user's journey through the application is functional and reliable.
- Trap to Control: Mastering the
Trapmethod is essential for handling dialogs, request pages, and modal windows that appear during user interactions. - Isolation is Key: Atomic, independent tests are the foundation of a stable test suite. Never let one test rely on the data created by another.
- Use Handlers for Dialogs:
HandlerFunctionsallow you to automate responses to confirmation prompts and alerts, keeping your tests fully automated and hands-free. - Focus on the Happy Path: Don't get lost in testing every single visual element. Focus on the core business processes and the primary paths your users will take.
- Maintainability Matters: Clean code, descriptive naming, and avoiding hardcoded values will ensure your test suite remains a valuable asset as your application evolves.
- Integrate Early: Make testing a part of your daily development cycle. The earlier you catch a UI workflow issue, the cheaper and easier it is to fix.
By following these principles, you will move from simply writing code to building a robust, high-quality solution that your users can trust. The investment you make in UI testing today will pay dividends in reduced maintenance and higher customer satisfaction tomorrow. Happy testing!
Not read yet
Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.
Spend your points to unlock exam-style practice questions
Spend points to unlock MB-820 exam-style practice questions.
Practice for MB-820