How to do it...

  1. Open your AL project in Visual Studio Code.
  2. In Explorer, select My Test.al. In the Editor, add the SubType property to the empty codeunit object in order to define it as a test codeunit:
codeunit 50150 "My Test"
{
SubType = Test;

}
  1. Now, let's add a new test function to the codeunit:
[Test]
procedure SuccessTest()
var
TelevisionShow: Record "Television Show";
LibraryUtility: Codeunit "Library - Utility";
begin
TelevisionShow.Init();

TelevisionShow.Validate(Code,
LibraryUtility.GenerateRandomCode20(
TelevisionShow.FieldNo(Code), Database::
"Television Show"));

TelevisionShow.Insert(true);
end;

  1. Let's create another test function:
[Test]
procedure FailureTest()
var
TelevisionShow: Record "Television Show";
LibraryUtility: Codeunit "Library - Utility";
begin
TelevisionShow.Get(LibraryUtility
.GenerateRandomCode20(TelevisionShow.FieldNo(Code),
Database::"Television Show"));
end;
  1. Now, let's run our tests! Press F5 to build and publish your test application in your development sandbox:
    1. Use the  icon to search for Test Tool and click the link to open it.
    2. Delete any existing entries in the page or create a new test suite.
    3. Select Process | Get Test Codeunits | Select Test Codeunits and press OK to view the list of all of the testing codeunits.
    4. Find the My Test entry and select it. Click OK.
    5. Select Run | All.

We got a failure, but remember, that's exactly what we expected to happen. This is to simply demonstrate the passing and failing of a test.

If you want to test a situation where you expect an error to happen, you need to properly handle the failing scenario by using the asserterror statement so that the system knows you expect the error to occur.

Read more about that here: https://docs.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/devenv-extension-advanced-example-test#asserterror-statement.