Share via


Mock outbound HttpClient web service calls during testing

Enabled for Public preview General availability
Admins, makers, marketers, or analysts, automatically Apr 1, 2025 Apr 1, 2025

Business value

To make it easier to test AL code that calls outbound web services, you can now mock those calls. With this feature, you can hardcode return values for calling code during tests without making the actual outbound web service call. Mocking calls is especially valuable when you test Copilot and AI features. Developers can write unit tests for these features without connecting to Azure OpenAI Service, so you save token consumption. This feature is available only for on-premises instances, including containers used for automated testing.

Feature details

AL developers can mock HttpClient Get, Put, Delete, and Post calls in unit tests. By adding a handler function, you can intercept HttpClient calls and easily substitute the responses for HttpClient calls in unit tests.

When you add an HttpClientHandler to a test method, the handler intercepts every HTTP request that occurs during the execution of that test. The handler receives a TestHttpRequestMessage that contains information about the HTTP request. It also receives a TestHttpResponseMessage that contains the mocked HTTP response values that the handler updates. The handler returns a Boolean value that indicates whether to fall through and issue the original HTTP request (true) or to use the mocked response (false).

The TestHttpRequestPolicy property on test codeunits determines how outbound HTTP requests are treated during test execution. It supports the following values:

  • BlockOutboundRequests: Any HTTP request issued during the test execution that an HTTP client handler doesn't catch and handle raises an exception.
  • AllowOutboundFromHandler: An HTTP client handler catches all HTTP requests issued during the test execution. The handler can allow the request to go through and issue the original request to the external endpoint.
  • AllowAllOutboundRequests: The test execution allows all outbound HTTP requests.

The following example shows a codeunit that makes an external web service call and a test codeunit that intercepts and mocks the call. Notice the use of the HttpClientHandler in the test codeunit.

Example of test case mocking the external web service call by using the HttpClientHandler

Example of code making external httpclient web call that we want to mock

Geographic areas

Visit the Explore Feature Geography report for Microsoft Azure areas where this feature is planned or available.

Language availability

Visit the Explore Feature Language report for information on this feature's availability.

Tell us what you think

Help us improve Dynamics 365 Business Central by discussing ideas, providing suggestions, and giving feedback. Use the forum at https://aka.ms/bcideas.

Additional resources

Mock outbound HttpClient web service calls during testing (docs)