Blog
Creating mock services for test automation in Business Central
Anyone planning to publish an extension in Microsoft’s AppSource will quickly realize that they need to create their own mock services for their test automation. Here is a very short guide that you can customize for your project if you are using the built-in HTTP client to send or receive data to a web service via GET/POST.
If you want to receive JSON data from a web service, you have to “fake” these calls, as real HTTP connections are not allowed during the tests.
We assume that you have written a code unit for establishing the HTTP connection. If this is the case – you have already achieved a large part! If not, you will probably have to restructure your code and move it to a separate code unit. Then you are ready to go! Now comes the crucial part: Wherever you call the function of the code units to call the web service, you must also pass the object ID of the code unit (e.g. using a field in a setup table and a table relation to “CodeUnit Metadata”.ID;). This allows your code to execute either the real code unit or the mock code unit.
Since it is (in most cases) not possible to pack the entire JSON (what is to be tested) into a string, you have to create it yourself “on the fly” in your mock code unit. 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 will not process anyway.
You can construct your JSON message by creating variables in your function and using “JsonObject”, “JsonArray”, “JsonValue” etc. as required.
To do this, we create a text array and enter all the data.
Example:
If part of the JSON is the key/value pair “{“id”: “12345”}”, then create the object as follows:JsonValueArray[1] := '12345';
JsonObject.Add('id', JsonValueArray[1]);
If we have multiple entries in a JSON message, we use a 2-dimensional text array and change the code slightly to run through it in a loop:JsonValueArray[1][1] := '12345';
JsonValueArray[2][1] := '67890';
Then inside the loop:JsonObject.Add('id', JsonValueArray[i][1]);
Of course, this is only a small part of what you actually need to do. But we hope this at least gives you some guidance on how to write your JSON mock services for Business Central tests, because Microsoft pretty much leaves you in the dark on what to do.