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.
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.