Skip to main content

Command Palette

Search for a command to run...

How to test for errors

Automated Tests in Dynamics 365 Business Central

Updated
2 min read

Not all test scenarios should have a positive outcome (sunny path). Sometimes we want to test that a certain scenario fails with an error (rainy path).

The challenge is that the nature of tests in the Business Central Test Framework is that errors result in a test failure.

To overcome this challenge we have to tell the Test Framework that an error is expected. This also means that no error is unexpected.

This is exactly what the asserterror keyword is for. It inverts the error mechanism and encapsulates the error allowing us to then assert that we get the expected error as shown the example below.

[Test]
procedure "Test for error"()
begin
   asserterror Error('An expected error');
   LibraryAssert.ExpectedError('An expected error');
end;

var
   LibraryAssert: Codeunit "Library Assert";

Errors are still erros

Even though the error mechanism is inverted when using asserterror the actual error will still occur. The consequence of this is that rollbacks will happen as usual.

In the example below we insert some data, test for an error with asserterror and then try to modify the data we inserted. However, the modification will fail with an error because the inserted data has been removed by the rollback.

[Test]
procedure "Errors are still errors"()
var
   Customer: Record Customer;
begin
   Customer.Insert();
   asserterror Error('An expected error');
   Customer.Modify(); // An error with be thrown by this statement
end;

If this behavior is unwanted all we need to do is add a commit and everything will work as expected.

[Test]
procedure "Errors are still errors"()
var
   Customer: Record Customer;
begin
   Customer.Insert();
   Commit();
   asserterror Error('An expected error');
   Customer.Modify(); // No error is thrown because the insert was committed.
end;

Automated Tests

Part 1 of 2

This series describes how to get started with automated tests in Dynamics 365 Business Central. You will also find advice on how to solve challenges when writing automated tests and testable code.

Up next

Installing the Test Toolkit

Automated Tests in Dynamics 365 Business Central

More from this blog

Kasper Mørch's Blog about Microsoft Dynamics 365 Business Central

4 posts

This blog is about development and automated testing for Dynamics 365 Business Central using Microsoft AL and Visual Studio Code. You may also find a few posts about Dynamics NAV, C/Side and C/AL.