{"title":"Write AI tests","url":"https://jonas-paprotka.de/docs/dev-itpro/developer/ai-test-copilot-ai-tests/","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/ai-test-copilot-ai-tests, 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/ai-test-copilot-ai-tests","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 write AL tests for Copilot features using datasets, assertions, and external evaluation.","date":"2026-10-02","meta":{"topic":"concept-article"},"outline":[{"level":1,"title":"Write AI tests","slug":"write-ai-tests","at":0,"chars":6624},{"level":2,"title":"Step-by-step: write an AI test","slug":"step-by-step-write-an-ai-test","at":279,"chars":5927},{"level":3,"title":"Step 1 - define the test","slug":"step-1---define-the-test","at":604,"chars":440},{"level":4,"title":"Example of a basic test method","slug":"example-of-a-basic-test-method","at":869,"chars":175},{"level":3,"title":"Step 2 - access the dataset","slug":"step-2---access-the-dataset","at":1044,"chars":1015},{"level":4,"title":"Example - access the dataset","slug":"example---access-the-dataset","at":1558,"chars":501},{"level":3,"title":"Step 3 - call the Copilot feature","slug":"step-3---call-the-copilot-feature","at":2059,"chars":746},{"level":3,"title":"Step 3b - access the selected Business Central agent","slug":"step-3b---access-the-selected-business-central-agent","at":2805,"chars":413},{"level":3,"title":"Step 4a - evaluate internally","slug":"step-4a---evaluate-internally","at":3218,"chars":1065},{"level":3,"title":"Step 4b - evaluate externally","slug":"step-4b---evaluate-externally","at":4283,"chars":1923},{"level":2,"title":"Related information","slug":"related-information","at":6206,"chars":418}],"text":"# Write AI tests\nAn AI Test is a procedure designed to evaluate the accuracy, reliability, and safety of a Copilot feature. These tests involve running the Copilot through a series of predefined scenarios defined by datasets, then comparing the outputs against expected results.\n## Step-by-step: write an AI test\n> TIP\n> The full source code for the example used in this article can be found in the Marketing text sample<https://github.com/microsoft/BCTech/tree/master/samples/AzureOpenAI/Conference%20Demos/Techdays/Marketing%20Text%20Simple/test> demo project.\nFollow these steps to create an AI test.\n### Step 1 - define the test\nAn AI test in Business Central is a standard AL test that uses the `AIT Test Context` codeunit to interact with datasets.\n> NOTE\n> AI tests depend on datasets. Learn more about how to create one in the ai-test-copilot-datasets article.\n#### Example of a basic test method\n```al\n[Test]\nprocedure TestTagLineLength()\nvar\n    AITTestContext: Codeunit \"AIT Test Context\";\nbegin\n    // Test logic goes here\nend;\n```\n### Step 2 - access the dataset\nUse the `AIT Test Context` codeunit to retrieve inputs and expected values from your dataset.\n To get the full input as JSON:\n  ```al\n  AITTestContext.GetInput()\n  ```\n To get specific setup values:\n  ```al\n  AITTestContext.GetTestSetup().Element('element_name').ValueAsText()\n  ```\n To get expected result values:\n  ```al\n  AITTestContext.GetExpectedData().Element('element_name').ValueAsInteger()\n  ```\n> TIP\n> Review the `AIT Test Context` codeunit for all supported procedures.\n#### Example - access the dataset\n```al\n[Test]\nprocedure TestTagLineLength()\nvar\n    AITTestContext: Codeunit \"AIT Test Context\";\n    MaxLength: Integer;\n    ItemNo: Code[20];\nbegin\n    // [GIVEN] The item and required maximum length\n    CreateItem();\n    ItemNo := CopyStr(AITTestContext.GetTestSetup().Element('item_no').ValueAsText(), 1, MaxStrLen(ItemNo));\n    MaxLength := AITTestContext.GetExpectedData().Element('tagline_max_length').ValueAsInteger();\n\n    // Continue with test logic\nend;\n```\n### Step 3 - call the Copilot feature\nYou can invoke your Copilot feature from AL code just like any other method.\nExample of calling GenerateTagLine:\n```al\n[Test]\nprocedure TestTagLineLength()\nvar\n    AITTestContext: Codeunit \"AIT Test Context\";\n    MarketingTextWithAI: Codeunit \"Marketing Text With AI\";\n    TagLine: Text;\n    MaxLength: Integer;\n    ItemNo: Code[20];\nbegin\n    // [GIVEN]\n    CreateItem();\n    ItemNo := CopyStr(AITTestContext.GetTestSetup().Element('item_no').ValueAsText(), 1, MaxStrLen(ItemNo));\n    MaxLength := AITTestContext.GetExpectedData().Element('tagline_max_length').ValueAsInteger();\n\n    // [WHEN]\n    TagLine := MarketingTextWithAI.GenerateTagLine(ItemNo, MaxLength);\n\n    // Continue with test logic\nend;\n```\n### Step 3b - access the selected Business Central agent\nWhen your evaluation targets a Business Central agent, use the `Agent Test Context` codeunit to access the selected agent identity during the test run.\n```al\nprocedure GetAgentDuringTest(var AgentUserSecurityID: Guid)\nvar\n    AgentTestContext: Codeunit \"Agent Test Context\";\nbegin\n    AgentTestContext.GetAgentUserSecurityID(AgentUserSecurityID);\nend;\n```\n### Step 4a - evaluate internally\nUse AL assertions to verify that the generated results meet expectations.\n```al\n[Test]\nprocedure TestTagLineLength()\nvar\n    AITTestContext: Codeunit \"AIT Test Context\";\n    MarketingTextWithAI: Codeunit \"Marketing Text With AI\";\n    TagLine: Text;\n    MaxLength: Integer;\n    ItemNo: Code[20];\n    TaglineLengthErr: Label 'Tagline: %1; Length: %2; Exceeds maximum length of %3', Comment = '%1 = Tagline, %2 = Length, %3 = Maximum Length';\nbegin\n    // [GIVEN]\n    CreateItem();\n    ItemNo := CopyStr(AITTestContext.GetTestSetup().Element('item_no').ValueAsText(), 1, MaxStrLen(ItemNo));\n    MaxLength := AITTestContext.GetExpectedData().Element('tagline_max_length').ValueAsInteger();\n\n    // [WHEN]\n    TagLine := MarketingTextWithAI.GenerateTagLine(ItemNo, MaxLength);\n\n    // [THEN]\n    if StrLen(TagLine) > MaxLength then\n        Error(TaglineLengthErr, TagLine, StrLen(TagLine), MaxLength);\nend;\n```\n> NOTE\n> Ensure all test methods in a codeunit can handle the same input. If not, split the tests across multiple codeunits.\n### Step 4b - evaluate externally\nFor more complex validations (for example, tone, relevance), it's often better to evaluate the results externally, using tools like Azure AI Foundry.\nUse SetTestOutput to export output for external evaluation:\n```al\n[Test]\nprocedure TestMarketingTextContentCasual()\nbegin\n    TestScenario(StyleEnum::Casual);\nend;\n\nlocal procedure TestScenario(Style: Enum \"Marketing Text Style\")\nvar\n    Item: Record Item;\n    TestContext: Codeunit \"AIT Test Context\";\n    MarketingTextWithAI: Codeunit \"Marketing Text With AI\";\n    TestOutputJson: Codeunit \"Test Output Json\";\n    ContextOutputJson: Codeunit \"Test Output Json\";\n    MarketingText: Text;\n    QueryTxt: Text;\n    ItemNo: Code[20];\nbegin\n    // [GIVEN]\n    CreateItem();\n    ItemNo := CopyStr(TestContext.GetTestSetup().Element('item_no').ValueAsText(), 1, MaxStrLen(ItemNo));\n\n    // [WHEN]\n    MarketingText := MarketingTextWithAI.GenerateMarketingText(ItemNo, Style);\n\n    // [THEN] External evaluation\n    QueryTxt := 'Generate a marketing text for the given item in Business Central in ';\n    case Style of\n        StyleEnum::Formal:\n            QueryTxt += '*Formal* Tone.';\n        StyleEnum::Verbose:\n            QueryTxt += '*Verbose* Tone.';\n        StyleEnum::Casual:\n            QueryTxt += '*Casual* Tone.';\n    end;\n\n    // Prepare test output\n    TestOutputJson.Initialize();\n    TestOutputJson.Add('query', QueryTxt);\n\n    // Add context\n    ContextOutputJson.Initialize();\n    ContextOutputJson.Add('item_no', ItemNo);\n    Item.Get(ItemNo);\n    ContextOutputJson.Add('description', Item.Description);\n    ContextOutputJson.Add('uom', Item.\"Base Unit of Measure\");\n\n    TestOutputJson.Add('context', ContextOutputJson.ToText());\n\n    // Add generated response\n    TestOutputJson.Add('response', MarketingText);\n\n    // Set test output for external validation\n    TestContext.SetTestOutput(TestOutputJson.ToText());\nend;\n```\n## Related information\nBusiness Central Copilot Evaluation<https://github.com/microsoft/BCApps/blob/main/src/Tools/AI%20Test%20Toolkit/README.md>\nBuild the Copilot capability in AL<ai-build-capability-in-al>\nTest the Copilot capability in AL<ai-test-copilot>\nCreate datasets<ai-test-copilot-datasets>\nEvaluation<ai-test-copilot-testtool>\nBest practices for testing the Copilot capability<ai-test-copilot-bestpractices>"}