{"title":"Create test codeunits and test methods","url":"https://jonas-paprotka.de/docs/dev-itpro/developer/devenv-test-codeunits-and-test-methods/","by":"JOP-AL","license":"Copyright (c) Microsoft Corporation. CC BY 4.0, https://creativecommons.org/licenses/by/4.0/; code samples MIT. From https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/devenv-test-codeunits-and-test-methods, MicrosoftDocs/dynamics365smb-devitpro-pb at 828b6ee (2026-11-19). Changed: includes filled in, links to this site, and for agents shortened without dropping a fact.","credit":"Microsoft Corporation, CC BY 4.0","origin":"https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/devenv-test-codeunits-and-test-methods","source":{"name":"Business Central developer and IT pro docs","repo":"https://github.com/MicrosoftDocs/dynamics365smb-devitpro-pb","commit":"828b6ee72fcd75755627cd6011f3d20899217ab2","date":"2026-11-19"},"checked":"2026-11-19","description":"Learn how to create test codeunits and test methods in AL, set the SubType property to Test, and use the different test method attributes in Business Central.","date":"2026-08-24","meta":{"topic":"concept-article"},"outline":[{"level":1,"title":"Create test codeunits and test methods","slug":"create-test-codeunits-and-test-methods","at":0,"chars":11141},{"level":2,"title":"Test properties","slug":"test-properties","at":2674,"chars":330},{"level":2,"title":"Add lifecycle handlers to test codeunits","slug":"add-lifecycle-handlers-to-test-codeunits","at":3004,"chars":4404},{"level":3,"title":"Use the test handler context","slug":"use-the-test-handler-context","at":5618,"chars":1790},{"level":2,"title":"Create data-driven tests","slug":"create-data-driven-tests","at":7408,"chars":3604},{"level":2,"title":"Related information","slug":"related-information","at":11012,"chars":129}],"text":"# Create test codeunits and test methods\nIn Dynamics 365 Business Central, you can create test codeunits and then test methods in the test codeunits.\nTest codeunits are codeunits that have the properties/devenv-subtype-codeunit-property set to Test. You write tests as AL code in the methods inside of the test codeunits. There are three types of methods that you can add in a test codeunit: test, handler, and normal. Each method type is used for a specific purpose and behaves differently. When a test codeunit runs, it runs the OnRun trigger, and then runs each test method in the codeunit.\nBy default, each test method runs in a separate database transaction, but you can use the attributes/devenv-transactionmodel-attribute on test methods and the properties/devenv-testisolation-property on test runner codeunits to control the transactional behavior.\nThe results of a test codeunit and of the individual test methods are displayed in a message window, but you can use the triggers-auto/codeunit/devenv-onaftertestrun-codeunit-trigger on a test runner codeunit to capture the results. The outcome of a test method is either SUCCESS or FAILURE. If any error is raised by either the code that is being tested or the test code, then the global outcome of the test codeunit is FAILURE and the error is included in the results log file.\nThe difference between a normal codeunit and a test codeunit is their execution at runtime. When a normal codeunit is run, if one of its methods fails, then the codeunit is terminated. When a test codeunit is run, even if the outcome of one test method is FAILURE, the next test methods are still running.\nThe methods in a test codeunit can be one of the following types:\nType|Description\nTest method|You use test methods that include AL code that tests the business logic in the application, where each method covers a transaction. You declare the attributes/devenv-test-attribute on the method.\nHandler method|You use handler methods to automate tests by handling instances when user interaction is required by the code that is being tested by the test method. In these instances, the handler method is run instead of the requested user interface. The handler method should simulate the user interaction for the test case, such as validating messages, making selections, or entering values. You declare a handler type attribute on the method. See Create handler methods<devenv-creating-handler-methods>.\nNormal method|You use normal methods to structure the test code by using the same design practices and principles as methods in other codeunits of the application. You declare the attributes/devenv-normal-attribute on the method.\n## Test properties\n> APPLIES TO: Business Central 2025 release wave 2 and later\nBy using runtime 16, you can use the properties/devenv-requiredtestisolation-property on test codeunits to specify the required test isolation level for the test codeunit. You can also use the properties/devenv-testtype-property to categorize tests.\n## Add lifecycle handlers to test codeunits\n> APPLIES TO: Business Central 2026 release wave 2 and later\n> NOTE\n> This feature is available in preview with a prerelease of runtime 18 and Business Central Server version 29.\nStarting with runtime 18.0, the properties/devenv-testhandlers-property lets a test codeunit register codeunits that receive callbacks during a test run. Use these callbacks for cross-cutting tasks such as logging, cleanup, performance measurement, and test reporting. The TestHandlers property is available only on codeunits where `Subtype = Test`. Set the runtime value in the app.json file to `18.0` or later to use this property and its supporting types.\nEach handler codeunit implements the ITestHandler interface. The interface provides the following lifecycle callbacks. The methods have default implementations, so a handler only needs to implement the callbacks that it uses.\nCallback|Invocation\nOnBeforeTestCodeunitRun|Once, before the test codeunit starts\nOnAfterTestCodeunitRun|Once, after the test codeunit finishes\nOnBeforeTestProcedureRun|Before each test procedure\nOnAfterTestProcedureRun|After each test procedure\nOnBeforeTestCaseRun|Before each case in a data-driven test\nOnAfterTestCaseRun|After each case in a data-driven test\nThe following example implements a handler, registers it as a value in the extensible TestHandler system enum, and assigns that value to a test codeunit.\n```al\ncodeunit 50100 \"Test Activity Logger\" implements ITestHandler\n{\n    procedure OnBeforeTestProcedureRun(Context: TestHandlerContext)\n    begin\n        Message('Starting %1.', Context.ProcedureName);\n    end;\n\n    procedure OnAfterTestProcedureRun(Context: TestHandlerContext)\n    begin\n        Message('Finished %1. Success: %2.', Context.ProcedureName, Context.Success);\n    end;\n}\n\nenumextension 50100 \"Sample Test Handlers\" extends TestHandler\n{\n    value(50100; ActivityLogger)\n    {\n        Implementation = ITestHandler = \"Test Activity Logger\";\n    }\n}\n\ncodeunit 50101 \"Sales Tests\"\n{\n    Subtype = Test;\n    TestHandlers = ActivityLogger;\n\n    [Test]\n    procedure SalesDocumentCanBeCreated()\n    begin\n        // Run the test.\n    end;\n}\n```\nYou can list multiple TestHandler values in TestHandlers, separated by commas. Codeunit-specific handlers run in the listed order. Both TestHandler and DefaultTestHandler are extensible system enums whose values map ITestHandler to implementing codeunits. To register a handler for every test codeunit, add its mapping to an extension of DefaultTestHandler instead. Default handlers run before handlers registered on a test codeunit.\n### Use the test handler context\nEach callback receives a read-only methods-auto/testhandlercontext/testhandlercontext-data-type value with information about the current scope.\nMember|Description and use\nmethods-auto/testhandlercontext/testhandlercontext-codeunitid-method|Contains the test codeunit ID in every callback.\nmethods-auto/testhandlercontext/testhandlercontext-codeunitname-method|Contains the fully qualified test codeunit name in every callback.\nmethods-auto/testhandlercontext/testhandlercontext-procedurename-method|Contains the test procedure name in procedure-level and case-level callbacks. It's empty in codeunit-level callbacks.\nmethods-auto/testhandlercontext/testhandlercontext-testcasename-method|Contains the value returned by ITestContext.Identifier in case-level callbacks. It's empty in other callbacks.\nmethods-auto/testhandlercontext/testhandlercontext-success-method|Indicates the result in OnAfterTestCodeunitRun, OnAfterTestProcedureRun, and OnAfterTestCaseRun. Its value is false in before callbacks.\nSkip(Reason)<methods-auto/testhandlercontext/testhandlercontext-skip-method>|Skips the current procedure or data-driven case when called from OnBeforeTestProcedureRun or OnBeforeTestCaseRun. The reason appears in the test result and log. Calling this method from an after callback has no effect.\nFor a standard test procedure, the procedure callbacks run between the codeunit callbacks. For a data-driven procedure, all case callbacks run inside its procedure callbacks:\n```text\nOnBeforeTestCodeunitRun\n  OnBeforeTestProcedureRun\n    OnBeforeTestCaseRun\n    OnAfterTestCaseRun\n    OnBeforeTestCaseRun\n    OnAfterTestCaseRun\n  OnAfterTestProcedureRun\nOnAfterTestCodeunitRun\n```\nCase callbacks run only for procedures that use the TestDataSource attribute.\n## Create data-driven tests\n> APPLIES TO: Business Central 2026 release wave 2 and later\n> NOTE\n> This feature is available in preview with a prerelease of runtime 18 and Business Central Server version 29.\nStarting with runtime 18.0, the attributes/devenv-testdatasource-attribute runs one test method with multiple context values. The attribute takes a codeunit that supplies the cases and a text dataset identifier:\n```al\n[TestDataSource(Codeunit::\"Late Fee Data Source\", 'late-fees')]\nprocedure LateFeeIsCalculated(Context: interface \"Late Fee Test Context\")\nbegin\nend;\n```\nThe test method must be public, must not return a value, and must have exactly one parameter. The parameter type must be `interface ITestContext` or an interface that extends it. The provider codeunit must implement ITestDataSource.\nThe runtime passes the attribute's dataset identifier and a methods-auto/datasourcecontext/datasourcecontext-data-type value to ITestDataSource.GetDataRows. The method returns a `List of [interface ITestContext]`, where each item defines one test case. methods-auto/datasourcecontext/datasourcecontext-codeunitid-method identifies the provider codeunit, and methods-auto/datasourcecontext/datasourcecontext-appid-method identifies the app that defines the test method.\nEach context implementation supplies ITestContext.Identifier. The identifier names the case in test results and in TestHandlerContext.TestCaseName. It must be deterministic and remain stable between runs.\nThe following example defines a context, returns two cases from a provider, and consumes the context in a data-driven test.\n```al\ninterface \"Late Fee Test Context\" extends ITestContext\n{\n    procedure Balance(): Decimal;\n}\n\ncodeunit 50110 \"Late Fee Test Case\" implements \"Late Fee Test Context\"\n{\n    var\n        BalanceValue: Decimal;\n        CaseIdentifier: Text;\n\n    procedure Initialize(NewIdentifier: Text; NewBalance: Decimal)\n    begin\n        CaseIdentifier := NewIdentifier;\n        BalanceValue := NewBalance;\n    end;\n\n    procedure Identifier(): Text\n    begin\n        exit(CaseIdentifier);\n    end;\n\n    procedure Balance(): Decimal\n    begin\n        exit(BalanceValue);\n    end;\n}\n\ncodeunit 50111 \"Late Fee Data Source\" implements ITestDataSource\n{\n    procedure GetDataRows(DataSetIdentifier: Text; Context: DataSourceContext): List of [interface ITestContext]\n    var\n        FirstCase: Codeunit \"Late Fee Test Case\";\n        SecondCase: Codeunit \"Late Fee Test Case\";\n        TestCase: interface ITestContext;\n        TestCases: List of [interface ITestContext];\n    begin\n        if DataSetIdentifier <> 'late-fees' then\n            exit(TestCases);\n\n        FirstCase.Initialize('zero-balance', 0);\n        TestCase := FirstCase;\n        TestCases.Add(TestCase);\n\n        SecondCase.Initialize('positive-balance', 100);\n        TestCase := SecondCase;\n        TestCases.Add(TestCase);\n\n        exit(TestCases);\n    end;\n}\n\ncodeunit 50112 \"Late Fee Tests\"\n{\n    Subtype = Test;\n\n    [TestDataSource(Codeunit::\"Late Fee Data Source\", 'late-fees')]\n    procedure BalanceIsNonnegative(Context: interface \"Late Fee Test Context\")\n    begin\n        if Context.Balance() < 0 then\n            Error('The balance for test case %1 must not be negative.', Context.Identifier());\n    end;\n}\n```\nWith runtime version 16, you can use the properties/devenv-requiredtestisolation-property on test codeunits, in addition to the properties/devenv-testisolation-property, to specify the required test isolation level for the test codeunit. You can also use the properties/devenv-testtype-property to categorize tests.\n## Related information\ndevenv-testing-application\nCreate handler methods<devenv-creating-handler-methods>\ndevenv-interfaces-in-al"}