Testing Applications in Business Central
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 11 read · keep scrolling
✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro
Testing Applications in Business Central
Introduction: Why Testing Matters in Business Central
In the world of enterprise resource planning (ERP) systems like Microsoft Dynamics 365 Business Central, the stakes for software quality are exceptionally high. When you build customizations or integrations for a business, you are essentially modifying the engine that runs their accounting, supply chain, and operations. A minor logic error in a calculation or a trigger that fires incorrectly can lead to incorrect financial reporting, inventory discrepancies, or a complete stoppage of business processes. Testing is not merely an optional step in the development lifecycle; it is the fundamental safeguard that ensures your code behaves as expected under various real-world conditions.
Testing in Business Central has evolved significantly with the transition from the legacy C/AL environment to the modern AL (Application Language) development environment. Today, we have access to a sophisticated testing framework that allows developers to automate the verification of their code, ensuring that new features do not break existing functionality—a concept known as regression testing. By adopting a disciplined testing strategy, you reduce the time spent on manual debugging, increase the confidence of your users, and lower the long-term cost of maintaining your applications.
This lesson will guide you through the architecture of the Business Central testing framework, the creation of test codeunits, the use of test runners, and the best practices for ensuring your code is reliable. Whether you are a solo developer or part of a large enterprise team, the principles discussed here will help you build more resilient applications.
Not read yet
The Philosophy of Automated Testing
Before diving into the code, it is important to understand the mindset required for testing. Many developers fall into the trap of "manual testing," where they build a feature, deploy it, and click through a few screens to see if it works. While this provides a quick sense of satisfaction, it is inherently flawed because it is inconsistent, time-consuming, and prone to human error. Automation allows you to run a comprehensive suite of tests in seconds, every time you make a change to your codebase.
Types of Tests in Business Central
To build a complete testing strategy, you should aim for a balance of different types of tests. These are generally categorized by their scope and purpose:
- Unit Tests: These verify the smallest pieces of logic in your application, such as a function that calculates a discount or validates a date format. They should be fast, isolated, and have no dependencies on external data or systems.
- Integration Tests: These verify that different modules or objects within Business Central work together correctly. For example, testing that a custom sales document correctly posts to the General Ledger involves multiple tables and codeunits.
- UI/Interface Tests: These simulate a user interacting with the system, such as opening a page, entering data into fields, and pressing buttons. These tests are more fragile and slower but are essential for verifying the user experience.
Callout: Automated vs. Manual Testing Manual testing relies on human intuition, which is great for finding unexpected "edge cases" or usability issues that an automated script might miss. However, automated testing is the only way to ensure that your application remains stable over time as you add new features. A mature development process uses automated tests for baseline stability and reserves human time for exploratory testing and design validation.
Not read yet
Setting Up the Testing Environment
To start writing tests in Business Central, you need to ensure your development environment is correctly configured. The AL Language extension for Visual Studio Code provides the necessary tools, but you must also include the Test libraries in your project dependencies.
Step-by-Step: Adding Test Dependencies
- Open your project in Visual Studio Code.
- Open the
app.jsonfile. - Ensure that the
dependenciessection includes the necessary test framework applications. Usually, you will need the "Test Runner" and the "Library Assert" modules provided by Microsoft. - Run the command
AL: Download Symbolsfrom the Command Palette to pull these libraries into your local environment.
Tip: Always keep your test libraries in a separate project or a separate folder structure from your main application code. This prevents your production application from accidentally including test code, which would bloat the size of your app and introduce unnecessary security risks.
Not read yet
Creating Your First Test Codeunit
In Business Central, tests are written inside objects called "Test Codeunits." A Test Codeunit is a specific type of codeunit designed to hold test functions. The compiler identifies these functions based on their properties and the way they are structured.
Anatomy of a Test Function
A test function typically follows the "Arrange, Act, Assert" pattern:
- Arrange: Set up the environment, create the necessary data (like a test customer or item), and initialize variables.
- Act: Execute the specific function or process you are testing.
- Assert: Verify that the result of the action matches your expectation.
Here is a simple example of a test that verifies a custom function which calculates a sales discount:
codeunit 50100 "Discount Calculation Tests"
{
Subtype = Test;
[Test]
procedure TestDiscountCalculation()
var
DiscountCalculator: Codeunit "Discount Calculator";
BaseAmount: Decimal;
DiscountPercent: Decimal;
ExpectedResult: Decimal;
ActualResult: Decimal;
{
// Arrange
BaseAmount := 1000;
DiscountPercent := 10;
ExpectedResult := 900;
// Act
ActualResult := DiscountCalculator.Calculate(BaseAmount, DiscountPercent);
// Assert
Assert.AreEqual(ExpectedResult, ActualResult, 'The discount calculation logic is incorrect.');
}
}
Understanding the [Test] Attribute
The [Test] attribute is the most critical part of this code snippet. It tells the Business Central test runner that this function is a test case. If you omit this attribute, the function will be ignored during test execution.
Warning: Never include production business logic inside a test function. Keep your test code strictly focused on executing and verifying your production code. If you find yourself writing complex logic inside a test, it usually means your production code is not modular enough and needs to be refactored.
Not read yet
Advanced Testing Techniques
As your application grows, your testing needs will become more complex. You will eventually need to handle database transactions, mock external services, and test user interactions.
Handling Database Transactions
One of the best features of the Business Central test framework is automatic transaction handling. By default, the test runner wraps each test function in a database transaction. If the test passes, the transaction is rolled back. This ensures that your tests do not leave "garbage data" (like dummy customers or invoices) in your database after the test finishes.
Using the Library Assert Codeunit
Microsoft provides a library called Library Assert that contains various assertion methods. Instead of writing simple if-then statements to check results, you should use these methods to provide clear error messages when a test fails.
Assert.AreEqual(Expected, Actual, Message): Checks if two values are equal.Assert.IsTrue(Condition, Message): Checks if a boolean condition is true.Assert.IsFalse(Condition, Message): Checks if a boolean condition is false.Assert.RecordIsEmpty(Record): Checks if a table is empty.
Mocking and Isolation
When testing code that interacts with external APIs or complex system tables, you cannot always rely on real data. You should use "Mocking" to simulate the behavior of these dependencies. While AL does not have a native "mocking framework" in the traditional sense, you can achieve isolation by creating "wrapper" codeunits for your API calls and then swapping those wrappers during testing.
Callout: The Power of Assertions Using a dedicated assertion library is better than writing custom
ifstatements because it standardizes the failure output. When a test fails in the Test Tool, you want the error message to be descriptive enough to tell you exactly what went wrong without needing to open the source code.
Not read yet
UI Testing with the Test Library
Testing user interactions (UI testing) is the most challenging part of the Business Central testing process. Because Business Central is a web-based application, UI tests must simulate the browser's behavior. The Library - Variable Storage and Library - UI objects are helpful here, but the core tool is the TestPage object.
A TestPage allows you to open a page in a virtual environment, set values in fields, and trigger actions. Here is an example of how to test a Customer Card:
[Test]
procedure TestCustomerCardPage()
var
Customer: Record Customer;
CustomerCard: TestPage "Customer Card";
begin
// Arrange
Customer.Init();
Customer.Name := 'Test Customer';
Customer.Insert();
// Act
CustomerCard.OpenEdit();
CustomerCard.GoToRecord(Customer);
CustomerCard.Name.Value('Updated Name');
CustomerCard.OK().Invoke();
// Assert
Customer.Find();
Assert.AreEqual('Updated Name', Customer.Name, 'The page did not update the record correctly.');
end;
Best Practices for UI Testing
- Keep it focused: Do not try to test an entire end-to-end business process in one UI test. Break it down into small, manageable steps.
- Use unique identifiers: Ensure that the fields and actions you are testing have clear names and properties.
- Clean up: Always ensure that your UI test closes the page it opened. If a test fails and leaves a page open, it can interfere with subsequent tests.
Not read yet
Common Pitfalls and How to Avoid Them
Even with a good framework, developers often run into recurring issues when implementing test processes. Being aware of these traps can save you hours of troubleshooting.
1. The "Brittle Test" Syndrome
A brittle test is one that fails frequently for reasons unrelated to the code being tested. This often happens when tests rely on specific record IDs, hardcoded dates, or the state of other records in the database.
- The Fix: Always create your own test data within the test function. Never rely on "pre-existing" data that might have been changed by another developer or a previous test run.
2. Ignoring Test Order
Tests should be independent of one another. You should be able to run them in any order, or run just one of them in isolation, without affecting the outcome.
- The Fix: If your test requires data, create it in the
[TestInitialize]or[TestSetup]functions, or directly within the test function itself. Never assume thatTestBwill run afterTestAand inherit its data.
3. Over-Reliance on UI Tests
UI tests are significantly slower and more fragile than unit tests. If your logic can be tested by calling a codeunit function, do not use a UI test.
- The Fix: Use the "Testing Pyramid" approach: have many unit tests, a moderate number of integration tests, and only a few critical UI tests.
4. Failing to Assert
Some developers write tests that execute code but fail to actually verify the outcome. They check if the code "runs without errors," which is not the same as checking if the code "works correctly."
- The Fix: Always include at least one
Assertstatement in every test function. If you are testing a void procedure that doesn't return a value, check the database to ensure the expected record changes occurred.
Not read yet
Comparison: Unit Tests vs. UI Tests
| Feature | Unit Tests | UI Tests |
|---|---|---|
| Speed | Extremely Fast | Slow |
| Complexity | Low | High |
| Maintenance | Easy | Difficult |
| Scope | Single Function/Logic | User Workflow |
| Reliability | High | Subject to UI changes |
Integrating Tests into the Development Workflow
Testing should not be an afterthought performed at the end of a project. It should be an integral part of your daily workflow.
The Test-Driven Development (TDD) Approach
TDD is a methodology where you write the test before you write the code.
- Write a test that defines the expected behavior of a new feature.
- Run the test and watch it fail (because the feature doesn't exist yet).
- Write the minimum amount of code required to make the test pass.
- Refactor the code to improve quality while ensuring the test continues to pass.
This approach forces you to think about the design of your code before you start writing it, often resulting in cleaner, more modular APIs.
Automated Pipelines
In a professional setting, you should automate the execution of your tests using CI/CD (Continuous Integration/Continuous Deployment) pipelines, such as Azure DevOps or GitHub Actions. Every time you push code to your repository, the pipeline should automatically spin up a Docker container with a Business Central instance, compile your app, and run the test suite. If any test fails, the build is marked as "failed," preventing the faulty code from ever reaching a deployment stage.
Note: When using CI/CD pipelines, ensure you are using the specific Business Central Docker images provided by Microsoft. These images are pre-configured to support automated test runners and provide a consistent environment that mimics your production setup.
Not read yet
Troubleshooting and Debugging Tests
When a test fails, the Business Central Test Tool provides a detailed error message. However, sometimes the error message is generic (e.g., "The record already exists"). To find the root cause, you need to use the AL Debugger.
Step-by-Step: Debugging a Test
- Set a breakpoint in the codeunit you are testing.
- Open the Test Tool page in the Business Central client.
- Select the test you want to run.
- Instead of clicking "Run Test," use the "Debug" action (if available in your tooling) or attach the debugger to the session.
- Step through the code line-by-line to see exactly where the state deviates from your expectations.
If you are struggling to reproduce a failure, check if your test environment has different settings than your production environment. For example, a test might fail because of a different "Posting Date" range or a different "General Posting Setup" configuration.
Not read yet
Best Practices for Long-Term Maintenance
As your application grows, your test suite will grow with it. If you don't manage your tests, they can become a burden.
- Meaningful Names: Name your test functions clearly, such as
TestCalculateVATWithZeroPercentorTestCustomerCardValidationWhenBlocked. This makes it immediately obvious what the test is checking. - Documentation: If a test is complex, add comments explaining the "why" behind the test.
- Regular Refactoring: Just like your production code, your tests need to be refactored. If you find yourself copying and pasting the same "Arrange" code in five different tests, move that code into a helper procedure in a library codeunit.
- Test Coverage: Aim for high test coverage, but do not obsess over reaching 100%. Some code is trivial and does not warrant a test. Focus your efforts on the "business-critical" parts of your application—the parts that, if broken, would cause the most pain for the client.
Not read yet
Key Takeaways
- Testing is a Safety Net: Automated tests are the only way to ensure that your Business Central applications remain stable and reliable as your codebase grows and changes.
- Structure Your Tests: Always use the "Arrange, Act, Assert" pattern. This makes your tests predictable, readable, and easy to maintain.
- Prioritize Unit Testing: Focus on testing small, isolated pieces of logic. UI tests should be used sparingly because they are slow and fragile.
- Use the Right Tools: Leverage the
Library AssertandTestPageobjects provided by Microsoft to standardize your assertions and simulate user interactions. - Test Independence: Every test should be self-contained. Never rely on state left behind by previous tests; always set up your own data.
- Integrate Early: Testing should happen during development, not just before deployment. Consider adopting TDD or at least ensuring that every feature has a corresponding test.
- Automate Everything: Use CI/CD pipelines to run your tests automatically on every code change. This provides the fastest feedback loop and prevents regressions from reaching your users.
By following these principles, you will transition from a developer who "hopes" their code works to a professional who "knows" their code works. Testing is the hallmark of a mature, high-quality development practice in Business Central. Start small, build your test suite incrementally, and you will find that the time you invest in testing pays for itself many times over in saved debugging time and increased user satisfaction.
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