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
randheer practiserandheer practise 

in the below class for upsert functionality iam getting 95% code coverage but iam unable to cover code in catch block while iam inserting the record,canany one help me from that

apex class
public class UpsertDml {
    public list<Account> acc{get;set;}
    //default constructor1
    public UpsertDml(){
        acc=new list<Account>();
    }
    public void upsertAccount()
    {
        Account a = new Account(Name='k');
        try{
             insert a;
        }catch(Exception e){
             system.debug('Recor '+a.Name +' inserted successfully');
        }
        List<Account> accounts=[SELECT id,name FROM Account WHERE name='kanusupdated'];
        If(accounts.size() > 0){
            try{
             for(Account a1:accounts)
                {
                if(a1.name=='kanusupdated')
                {
                    Account a2=new Account();
                    a2.id=a1.id;
                    a2.name='kanus updated';
                    acc.add(a2);
                }
             }
                    update acc;
            system.debug('records were updated successfully===='+acc);     
            }catch(DMLException e){
                system.debug('records were not updated====='+e);
            }
     
       }
   }
}
============testclass
@isTest
public class upsertDml_Test {
    public static testmethod list<Account> recordCreation(){      
        List<Account> ac = new List<Account>();
        Account a = new Account();
        a.Name = 'kanusupdated';
        ac.add(a);
        return ac;      
    }
    
    public static testmethod void P_main(){
        Test.startTest();
        Account a = new Account(name='kanusupdated');
        list<Account> acc1 = recordCreation();
        insert acc1;     
        upsertDml sc = new upsertDml();
        sc.acc = recordCreation();
        system.debug('values in sc.acc ============='+sc.acc);
        sc.upsertAccount();
        Test.stopTest();
    }    
}

thanks in advance..just cover the code at catch block while iam inserting record with name 'k'..thanks in advance