Creating mock services for test automation in Business Central

Everyone who plans to publish an extension in Microsofts‘ AppSource you’ll quickly notice that you need to come up with your own mock services for your test automation. Here’s a very short guide that you can adapt for your project if you are using HTTP Client to GET or POST data to a webservice.

Given you want to receive JSON data from a web service you’ll need to „fake“/mock those calls because real connections are not allowed during testing.

We assume that you have written a codeunit for establishing the HTTP connection. If that’s the case – you are lucky! If not you probably need to refactor your code and put it inside a separate codeunit. After that you are good to go! Here comes the crucial part: Everywhere you are calling the codeunits‘ function for calling the web service you’ll need to pass the object id of the codeunit with it (e.g. through a field in a setup table and a table relation to „CodeUnit Metadata“.ID;). This enables your code to execute either the real codeunit or the mock codeunit.

Since it’s (in most cases) not feasible to put the whole JSON into a string you’ll need to create it „on the fly“ by yourself in your Mock Connection codeunit. Write a function that Generates your JSON based on a real JSON message from the web service. Leave out the unnecessary objects that your code won’t process anyhow.

You can construct your JSON message by creating variables in your function and use „JsonObject“, „JsonArray“, „JsonValue“ etc. as you need.

I usually create a Text array and fill all the data in. E.g.: If part of the JSON is the key/value pair „{ "id": "12345"}“ then I will create the Object like that:
JsonValueArray[1] := '12345';
JsonObject.Add('id', JsonValueArray[1]);

If I have multiple entries in one JSON message then I use a 2-dimensional Text array and slightly modify the code and loop through it:
JsonValueArray[1][1] := '12345';
JsonValueArray[2][1] := '67890';
JsonObject.Add('id', JsonValueArray[i][1]);

Of course, this is just a small fraction of what you actually need to do. But I hope that at least gives you a little bit of guidance on how to write your JSON Mock Services for Business Central, since Microsoft leaves you pretty much in the dark. If you have any further questions, hit me up!

Teile deine Gedanken

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.