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;