How do I: test code that calls external web services

With the current test framework and it’s limitations it can sometimes be hard to find a way to test your code, this gets even worse when external web services are called.
I’ve seen a number of (bad) workarounds in the last few months varying from calling a nonexistent endpoint to a self-hosted web service to test against.
Of course those workarounds do their job but we can do better than that, and let’s not forget tests must be independent of external components!

Ideally we would simply mock this web service call and return some data we can test against, but not in (C/)AL right?

Inspired by the handled pattern I came up with an idea to actually solve this in the best possible way, if you’re not familiar with the handled pattern in NAV you can read up on it here.
So let’s imagine the function that calls the external web service (or any other external component) implements the handled pattern and publishes an event which allows an event subscriber to take care of the further handling.

To get an idea of the concept I’ve created a skeleton framework in AL which only contains two codeunits:
– a codeunit which ‘calls’ an external web service
– a test codeunit with a function that tests the response of the web service

What we want to achieve is that during the executing of automated tests we want our test codeunit to take care of the further handling and set handled to true, so the DoCallWebService function exits straight away.

As you can see below I’ve split up the test codeunit into three pieces so we can analyze it step by step.

  1. Event subscriber instance must be set to manual, meaning events should be bound manually by using the BindSubscription function.
    The codeunit which will be bound has to be either local within every test function or global within the test codeunit in order to bind it without losing state.
  2. First bind the subscription for the current codeunit, call the code which calls the web service and the unbind it again.
    The if BindSubscription then; is used to prevent errors, when for example a previous test failed and the codeunit is still bound, this could also be solved in the initialize function (which I skipped for this example)
  3. The event subscriber, subscribed to the OnBeforeCallWebService event, only triggered when the current codeunit is bound.

The only disadvantage is that we have to modify our production code in order to test it, but implementing a handled pattern is fairly safe.

Happy testing!

Leave a Reply

Your email address will not be published. Required fields are marked *