Triggering a DML Exception for Test Coverage

I have an Apex Class, where 55% of the code is inside a catch, requiring a DML exception to be executed. Since the DML update request is using data from an SOQL request inside this class, I have no idea how I can trigger a DML exception.

Is it possible to lock a certain record from updating (or all the database), in a way that could trigger a DML exception?



You can use FOR UPDATE to lock a certain record, but it would be locked to the testing transaction, so it might not give you the DML Exception you want.

How dependant are you on the content of the DML Exception? If you just want an exception of the correct type use Test.isRunningTest() to deliberately cause the exception.

try {

    // If you can't manipulate the Apex methods input or database state to cause a
    // DMLExcpetion then you can deliberately cause the DMLException to improve your
    // code coverage and check the functionality of the exception handling.
    // You could also use a flag set from your test method to indicate that the 
    // exception should be thrown
    if(Test.isRunningTest()) {
        // Cause DMLException
        insert new Lead();

} catch (DMLException ex) {
    // Existing exception handling.        

As you mentioned, it is less than ideal to modify the body of the Apex Method you are testing to facilitate testing. If you can, manipulate either the methods inputs or the state of the database from the test method to cause the DMLException.

You mentioned that the update is using data that is retrieved from a SOQL request in the class. If you put the test method within the class definition you can manipulate the private members directly from the test.

Source : Link , Question Author : jpmonette , Answer Author : Daniel Ballinger

Leave a Comment