{"title":"Mock outbound HttpClient web service calls during testing","url":"https://jonas-paprotka.de/docs/dev-itpro/developer/devenv-httpclient-mock-outbound-calls/","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-httpclient-mock-outbound-calls, 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-httpclient-mock-outbound-calls","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 about how to test HttpClient web calls to external services without invoking the live/actual/remote service.","date":"2025-03-17","meta":{"topic":"concept-article"},"outline":[{"level":1,"title":"Mock outbound HttpClient web service calls during testing","slug":"mock-outbound-httpclient-web-service-calls-during-testing","at":0,"chars":6876},{"level":2,"title":"Defining the handler","slug":"defining-the-handler","at":1572,"chars":619},{"level":2,"title":"Handling the test execution","slug":"handling-the-test-execution","at":2191,"chars":1112},{"level":2,"title":"Example","slug":"example","at":3303,"chars":3365},{"level":3,"title":"Security limitations","slug":"security-limitations","at":5690,"chars":978},{"level":2,"title":"Related information","slug":"related-information","at":6668,"chars":208}],"text":"# Mock outbound HttpClient web service calls during testing\n> APPLIES TO: Business Central 2025 release wave 1 (v26) and later.\n> NOTE\n> This feature is only supported in Business Central on-premises.\nTestability of AL code that interacts with external web services is enhanced when the responses from these services can be simulated in AL, eliminating the need to configure actual endpoints. Mocking outbound web calls is useful when testing that your code is capable of handling a wide range of possible responses, and allowing you to track outbound traffic during the test executions.\nTo mock outbound HttpClient calls, you start by defining an HttpClientHandler that intercepts and processes the requests and simulates a response. Such a handler can be created by declaring a procedure with the appropriate signature and marking it with the attributes/devenv-httpclienthandler-attribute attribute. In the body of the procedure you can analyze the intercepted request and mock the response by populating the response object with the desired values. Finally, the handler can be attached to any test method in the codeunit using the attributes/devenv-handlerfunctions-attribute attribute. When a handler is attached to a test then all HttpClient calls that occur during the execution of that test is routed to the handler instead of the actual endpoint. However, there can be scenarios where you might only want to handle certain requests while letting others through to the external endpoint. This can be achieved by setting the return value of the handler accordingly.\n## Defining the handler\nThe HttpClientHandler procedure receives a TestHttpRequestMessage that contains information about the HTTP request, and a TestHttpResponseMessage that contains the mocked HTTP response values that should be updated by the handler. The boolean return value indicates whether to issue the original HTTP request; true or use the mocked response; false.\n> NOTE\n> The default return value of the HttpClientHandler procedure is false, ensuring that external service calls are only made intentionally. Therefore, an empty handler would still intercept the outbound request and mock a default response.\n## Handling the test execution\nIn addition to defining the handler, you can control how outbound HTTP requests are treated during test execution by using the properties/devenv-testhttprequestpolicy-property property. By default, all outbound requests are allowed, but you can further restrict this behavior to only allow ones issued from a handler, or to block all unhandled outbound requests.\nThe property has the following possible values:\nValue|Description\nBlockOutboundRequests|Any HTTP request issued during the test execution that isn't caught and handled by an HTTP client handler raises an exception. This can be useful when you don't want frequent test executions in CI/CD pipelines to hit the actual endpoint.\nAllowOutboundFromHandler|All HTTP requests issued during the test execution are required to be caught by an HTTP client handler. The handler is allowed to explicitly fall through to issue the original request to the external endpoint. This ensures that no unintentional http requests are made.\nAllowAllOutboundRequests|All outbound HTTP requests issued during the test execution are allowed.\n## Example\nIn the following example we have a procedure GetDocumentContent in the codeunit DocumentService that makes an external web service call. To verify that the GetDocumentContent works as expected, we can create a test in our DocumentServiceTest codeunit that makes an invocation to the GetDocumentContents and checks the content. Finally, we define an HttpClientHandler that simulates the desired `200 SUCCESS` response and attach it to the previously defined test. When the test is executed the handler will intercept the outbound request and mock the response.\n```al\ncodeunit 1 DocumentService\n{\n    procedure GetDocumentContent(DocumentId: Text): Text\n    var\n        Client: HttpClient;\n        Response: HttpResponseMessage;\n        Success: Boolean;\n        Content: Text;\n    begin\n        Success := Client.Get('http://example.com/documents?DocumentId=' + DocumentId, Response);\n\n        if (not Success) or (not Response.IsSuccessStatusCode) then\n            Error('Unsuccessful request');\n\n        Response.Content.ReadAs(Content);\n\n        exit(Content);\n    end;\n}\n\ncodeunit 2 DocumentServiceTest\n{\n    Subtype = Test; // Test codeunit\n    TestHttpRequestPolicy = AllowOutboundFromHandler; // Allow outbound requests from handler\n\n    [Test]\n    [HandlerFunctions('Handler')]\n    procedure TestGetDocumentContent()\n    var\n        DocService: Codeunit \"DocumentService\";\n    begin\n        if (DocService.GetDocumentContent('EXAMPLE_ID') <> 'EXAMPLE CONTENT EXAMPLE_ID') then\n            Error('Unexpected document content');\n    end;\n\n    [HttpClientHandler]\n    procedure Handler(Request: TestHttpRequestMessage; var Response: TestHttpResponseMessage): Boolean\n    var\n        DocumentId: Text;\n    begin\n        if (Request.RequestType = HttpRequestType::Get) and (Request.Path = 'http://example.com/documents') then begin\n            // Extract the DocumentId from the query parameters\n            Request.QueryParameters.Get('DocumentId', DocumentId);\n\n            // Populate the mocked response with the example content\n            Response.Content.WriteFrom('EXAMPLE CONTENT ' + DocumentId);\n            response.HttpStatusCode := 200;\n            response.ReasonPhrase := 'SUCCESS';\n\n            exit(false); // Use the mocked response\n        end;\n\n        exit(true); // fall through and issue the original request in case of other requests\n    end;\n}\n\n```\n### Security limitations\nThe request object, which is received by the handler contains limited information for security reasons. It excludes headers, content, and cookies to ensure that sensitive information isn't exposed during testing. The request object includes path, query parameters, and request type, such as GET and POST. Furthermore, if the URI of a request is set using a methods-auto/secrettext/secrettext-data-type, then neither the path nor the query parameters are available, to prevent leaking any secrets. You can filter for this case using the HasSecretUri property. The response object is subject to certain limitations as well, notably the inability to set cookies or specify redirection status codes (3**).\nThe handler can decide to send the request to the external endpoint instead of mocking the response. This is useful in scenarios where the request has a secret URI or where certain parts of the response, such as authorization tokens, can't be mocked.\n## Related information\nCall external services with the HttpClient data type<devenv-httpclient-mock-outbound-calls>\nmethods-auto/httpclient/httpclient-data-type\nproperties/devenv-testhttprequestpolicy-property"}