How to throw DML Exception Manually
The easiest way to intentionally throw DML exception is insert record without setting required field.
- Exception Class and Built-In Exceptions
Quote:
Any problem with a DML statement, such as an insert statement missing a required field on a record.
To bring more clarity here is code spinet for your reference:
try{
Account a = [Select id, name from account limit 1];
a.name = '';
update a;
}
Catch(Exception e){
system.debug('Exception ' + e);
}
There could be other ways to raise a DML Exception. For Example consider testAccount is a Account object in your test data. Now Below code will raise DML exception:
testAccount.Name='===================================================================================================Some string which is longer than 255 characters================================================================================================================';
update testAccount;
A DML Exception will be thrown and catch block would be covered. So you need to modify your test data accordingly.
Here is some sample code:
try{
if(Test.isRunningTest() && updatedAccSt.size() > 0 &&
updatedAccSt[0].Name='Exception Account'){
updatedAccSt[0].Name='===================================================================================================Some string which is longer than 255 characters================================================================================================================';
}
update updatedAccSt;
}
Its easy.
throw new DMLException('My DML EXCEPTION');