function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
bonny mankotiabonny mankotia 

test class code coverage need of catch block

I need a code coverage of catch block of this class.
public class AccountHandler {

    public static Account insertNewAccount (String accName){
        
        
    if(accName!=''){    
        try{
            Account a = new Account(Name=accName);
            insert a;
            System.debug('Bravo Andrè! Account created');
            return a;
        } catch(Exception e){
            System.Debug('Account not created');
            return null;
        }
    } else {
        return null;
    }
    }    
}

This is my test class.

@isTest
public class accounthandlerTest 
{
static testMethod void accounthandlerTest()
{
   /*account a = new account();
   a.Name='bonsy';
   insert a;*/
   //system.assert(a.id!= null,'The Test Account did not insert properly, please check validation rules and other mechanisms');
   AccountHandler.insertNewAccount('bonsy'); 
    AccountHandler.insertNewAccount('');       
 }
}
RatanRatan
You could add this to the code:

    
try {
        insert lst;
        TestOptions.throwDmlException();
    } catch(Exception e){
        ...
    }



where the added class is (as a `DmlException` can be constructed):

    
public class TestOptions {
        public static Boolean throwDmlException = false;
        public static void throwDmlException() {
            if (throwDmlException) throw new DmlException();
        }
    }



and then in your test case turn the option on where needed:

  
TestOptions.throwDmlException = true;