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
Carolyn juliana 7Carolyn juliana 7 

How to write Test class for Try catch block Apex

i am having 90% code coverage because atch block is not covered,can anyone help in writing code for catch block as well

Apex code -->
public class PickListHandler {
    @AuraEnabled
    public static List<String> getLevel1(){
    List<String> tempLst1 = new List<String>();
        for(AggregateResult  ar : [select Level_1__c,COUNT(id) from Case_Type_Data__c  group by Level_1__c])
    {
        tempLst1.add(''+ar.get('Level_1__c'));
    }

    return tempLst1;
      
      
    } 
    
    @AuraEnabled
    public static List<String> getLevel2(string strName){
    List<String> tempLst2 = new List<String>();
       for(AggregateResult  ar : [select Level_2__c,COUNT(id) from Case_Type_Data__c where Level_1__c=:strName  group by Level_2__c])
    {
       tempLst2.add(''+ar.get('Level_2__c'));
    }

    return tempLst2;
      
    } 
    
    @AuraEnabled
    public static List<String> getLevel3(string strName1,string strName2){
     List<String> tempLst3 = new List<String>();
      for(AggregateResult  ar : [select Level_3__c,COUNT(id) from Case_Type_Data__c  where Level_1__c=:strName1 and Level_2__c=:strName2 group by Level_3__c])
    {
       tempLst3.add(''+ar.get('Level_3__c'));
    }

    return tempLst3;
      
      
    } 
         
     @AuraEnabled
     Public  static String  savecasetype(string level1,string level2,string level3,string caseid){
     string strMsg='successfull';
          try{
     ERT_Case_Type__c obj=new ERT_Case_Type__c();
     Obj.Case__c =caseid;
     Obj.Level_1__c=level1;
     Obj.Level_2__c=level2;
     Obj.Level_3__c=level3;
     Insert obj;
     Return 'Successfully Inserted Levels';
     }
     
    catch(Exception ex){
            strMsg='error';
        }
     return strMsg;  
}

}

Test class code -->
@isTest
public class testGetAllLevels { 

static testMethod void testGetLevel1()
{
    Case_Type_Data__c obj = new Case_Type_Data__c();
    obj.Level_1__c = 'Test Level 1';
    insert obj;
    List<String> s = PickListHandler.getLevel1();

}
    
static testMethod void testGetLevel2()
{
    Case_Type_Data__c obj = new Case_Type_Data__c();
    obj.Level_1__c = 'Test Level 1';
    insert obj;
    List<String> s = PickListHandler.getLevel2('Test Level 1');

}
    
static testMethod void testGetLevel3()
{
    Case_Type_Data__c obj = new Case_Type_Data__c();
    obj.Level_1__c = 'Test Level 1';
    obj.Level_2__c = 'Test Level 2';
    obj.Level_3__c = 'Test Level 3';
    insert obj;
    List<String> s = PickListHandler.getLevel3('Test Level 1','Test Level 2');

}
    
    
static testMethod void testsaveCaseType(){
        // Create the Case Record.
        Case cas = new Case(Status ='New', Priority = 'Medium', Origin = 'Email'); 
        insert cas;
       
        ERT_Case_Type__c obj=new ERT_Case_Type__c();
        string one='one';
        string two='two';
        string three='three';
        test.startTest();
        String testing=PickListHandler.savecasetype(one,two,three,cas.id);
        test.stopTest();
    }
    
 
    
}

Thanks in advance
Carolyn
Best Answer chosen by Carolyn juliana 7
Andrew GAndrew G
To cover the exception, you would need to manufacture the situation where the insert of the ERT_Case_Type__c would fail.

For example, are there any validation rules that you could force the record to evaluate?  Or create a runAs user who does not have access to insert the ERT_Case_Type__c  record.

As an aside, have you considered the use of the TestSetup tag?
and also note that the testMethod keyword is now deprecated. Use the @isTest annotation on classes and methods instead. The @isTest annotation on methods is equivalent to the testMethod keyword.

Here is an example to play with:
@IsTest
public class testGetAllLevels { 

@TestSetup
static void setupTestData(){
    Profile profileId = [SELECT Id FROM Profile WHERE Name = 'Can't insert Case Type Profile' LIMIT 1];
    
    User usr = new User(LastName = 'TEST',
                           FirstName='Fail',
                           Alias = 'ftest',
                           Email = 'f.test@asdf.com',
                           Username = 'f.test@asdf.com',
                           ProfileId = profileId.id,
                           TimeZoneSidKey = 'GMT',
                           LanguageLocaleKey = 'en_US',
                           EmailEncodingKey = 'UTF-8',
                           LocaleSidKey = 'en_US'
                           );
    insert usr;
    // Create the Case Record.
    Case cas = new Case(Status ='New', Priority = 'Medium', Origin = 'Email'); 
    insert cas;

    Case_Type_Data__c obj = new Case_Type_Data__c();
    obj.Level_1__c = 'Test Level 1';
    obj.Level_2__c = 'Test Level 2';
    obj.Level_3__c = 'Test Level 3';
    insert obj;
}
@IsTest
static void testGetLevel1()
{
    List<String> s = PickListHandler.getLevel1();
    System.assertEquals('1',s);
}
@IsTest    
static void testGetLevel2()
{
    List<String> s = PickListHandler.getLevel2('Test Level 1');
    System.assertEquals('1',s);
}
@IsTest    
static void testGetLevel3()
{
    List<String> s = PickListHandler.getLevel2('Test Level 1','Test Level 2');
    System.assertEquals('1',s);
}
    
@IsTest    
static void testsaveCaseType(){
	Case testCase = [SELECT Id FROM Case WHERE Status = 'New' LIMIT 1];
       
    String one='one';
    String two='two';
    String three='three';

    test.startTest();
    String testing=PickListHandler.savecasetype(one,two,three,testCase.Id);
    test.stopTest();
    //need some sort of assert:
    System.assertEquals('Successfully Inserted Levels', testing);

}

@IsTest
static void testSaveFail(){
	User testUser = [SELECT Id FROM User WHERE alias = 'ftest'];
    Case testCase = [SELECT Id FROM Case WHERE Status = 'New' LIMIT 1];
       
    String one='one';
    String two='two';
    String three='three';

        test.startTest();
	System.runAs(testUser){
        try{
            String testing=PickListHandler.savecasetype(one,two,three,testCase.Id);
        } catch (DmlException ex) {
            System.assertEquals('expected text', ex.getMessage());
        }  
        test.stopTest();
    }
     
}

**code is provided uncompiled and as-is

Regards

Andrew

 

All Answers

Andrew GAndrew G
To cover the exception, you would need to manufacture the situation where the insert of the ERT_Case_Type__c would fail.

For example, are there any validation rules that you could force the record to evaluate?  Or create a runAs user who does not have access to insert the ERT_Case_Type__c  record.

As an aside, have you considered the use of the TestSetup tag?
and also note that the testMethod keyword is now deprecated. Use the @isTest annotation on classes and methods instead. The @isTest annotation on methods is equivalent to the testMethod keyword.

Here is an example to play with:
@IsTest
public class testGetAllLevels { 

@TestSetup
static void setupTestData(){
    Profile profileId = [SELECT Id FROM Profile WHERE Name = 'Can't insert Case Type Profile' LIMIT 1];
    
    User usr = new User(LastName = 'TEST',
                           FirstName='Fail',
                           Alias = 'ftest',
                           Email = 'f.test@asdf.com',
                           Username = 'f.test@asdf.com',
                           ProfileId = profileId.id,
                           TimeZoneSidKey = 'GMT',
                           LanguageLocaleKey = 'en_US',
                           EmailEncodingKey = 'UTF-8',
                           LocaleSidKey = 'en_US'
                           );
    insert usr;
    // Create the Case Record.
    Case cas = new Case(Status ='New', Priority = 'Medium', Origin = 'Email'); 
    insert cas;

    Case_Type_Data__c obj = new Case_Type_Data__c();
    obj.Level_1__c = 'Test Level 1';
    obj.Level_2__c = 'Test Level 2';
    obj.Level_3__c = 'Test Level 3';
    insert obj;
}
@IsTest
static void testGetLevel1()
{
    List<String> s = PickListHandler.getLevel1();
    System.assertEquals('1',s);
}
@IsTest    
static void testGetLevel2()
{
    List<String> s = PickListHandler.getLevel2('Test Level 1');
    System.assertEquals('1',s);
}
@IsTest    
static void testGetLevel3()
{
    List<String> s = PickListHandler.getLevel2('Test Level 1','Test Level 2');
    System.assertEquals('1',s);
}
    
@IsTest    
static void testsaveCaseType(){
	Case testCase = [SELECT Id FROM Case WHERE Status = 'New' LIMIT 1];
       
    String one='one';
    String two='two';
    String three='three';

    test.startTest();
    String testing=PickListHandler.savecasetype(one,two,three,testCase.Id);
    test.stopTest();
    //need some sort of assert:
    System.assertEquals('Successfully Inserted Levels', testing);

}

@IsTest
static void testSaveFail(){
	User testUser = [SELECT Id FROM User WHERE alias = 'ftest'];
    Case testCase = [SELECT Id FROM Case WHERE Status = 'New' LIMIT 1];
       
    String one='one';
    String two='two';
    String three='three';

        test.startTest();
	System.runAs(testUser){
        try{
            String testing=PickListHandler.savecasetype(one,two,three,testCase.Id);
        } catch (DmlException ex) {
            System.assertEquals('expected text', ex.getMessage());
        }  
        test.stopTest();
    }
     
}

**code is provided uncompiled and as-is

Regards

Andrew

 
This was selected as the best answer
Carolyn juliana 7Carolyn juliana 7
thanks i have edited my test class below getting below errors at line 34,40,46
 
Comparison arguments must be compatible types: String, List<String>
 
@IsTest
public class testGetAllLevels { 

@TestSetup
static void setupTestData(){
    Profile profileId = [SELECT Id FROM Profile WHERE Name = 'Cant' LIMIT 1];
    
    User usr = new User(LastName = 'TEST',
                           FirstName='Fail',
                           Alias = 'ftest',
                           Email = 'f.test@asdf.com',
                           Username = 'f.test@asdf.com',
                           ProfileId = profileId.id,
                           TimeZoneSidKey = 'GMT',
                           LanguageLocaleKey = 'en_US',
                           EmailEncodingKey = 'UTF-8',
                           LocaleSidKey = 'en_US'
                           );
    insert usr;
    // Create the Case Record.
    Case cas = new Case(Status ='New', Priority = 'Medium', Origin = 'Email'); 
    insert cas;

    Case_Type_Data__c obj = new Case_Type_Data__c();
    obj.Level_1__c = 'Test Level 1';
    obj.Level_2__c = 'Test Level 2';
    obj.Level_3__c = 'Test Level 3';
    insert obj;
}
@IsTest
static void testGetLevel1()
{
    List<String> s = PickListHandler.getLevel1();
    System.assertEquals('1',s);
}
@IsTest    
static void testGetLevel2()
{
    List<String> s = PickListHandler.getLevel2('Test Level 1');
    System.assertEquals('1',s);
}
@IsTest    
static void testGetLevel3()
{
    List<String> s = PickListHandler.getLevel3('Test Level 1','Test Level 2');
    System.assertEquals('1',s);
}
    
@IsTest    
static void testsaveCaseType(){
	Case testCase = [SELECT Id FROM Case WHERE Status = 'New' LIMIT 1];
       
    String one='one';
    String two='two';
    String three='three';

    test.startTest();
    String testing=PickListHandler.savecasetype(one,two,three,testCase.Id);
    test.stopTest();
    //need some sort of assert:
    System.assertEquals('Successfully Inserted Levels', testing);

}

@IsTest
static void testSaveFail(){
	User testUser = [SELECT Id FROM User WHERE alias = 'ftest'];
    Case testCase = [SELECT Id FROM Case WHERE Status = 'New' LIMIT 1];
       
    String one='one';
    String two='two';
    String three='three';

        test.startTest();
	System.runAs(testUser){
        try{
            String testing=PickListHandler.savecasetype(one,two,three,testCase.Id);
        } catch (DmlException ex) {
            System.assertEquals('expected text', ex.getMessage());
        }  
        test.stopTest();
    }
}
     
}
Andrew GAndrew G
modify your asserts to handle string versus list , s is a List of strings (the returned list), since the list should only hold one value, test for the first value.
so :
 
System.assertEquals('1',s[0]);
Regards
Andrew
 
Shilpa GoyalShilpa Goyal
Hi Andrew,
This is my apex class, can you please help me to write a test class with 100% coverage. i have wrote test class which gives 71% coverage.
Apex class:

public with sharing class PMInfoLWCController {
    //Wired method use to retrieve vehicle details for the case
    @AuraEnabled (Cacheable = true)
    public static List<Vehicle__c> getVehicleDetailsByCase(String recordId){
        try {
            system.debug('In getVehicleDetailsByCase'+recordId);
            Case caseDetails = [SELECT Id, casenumber,Vehicle__c FROM Case WHERE Id = :recordId];
            system.debug('****caseDetails :'+caseDetails);
            List<Vehicle__c> vehicleList   = [SELECT id,isForeignVehicle__c,UNIT_CORP__c,VFCORP__c,FVEHID__c,VFCUNIT__c,Name  FROM Vehicle__c WHERE id=:caseDetails.Vehicle__c];
            system.debug('****v'+vehicleList);
            return vehicleList;
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
    }
}

Test Class

@isTest
public class PMInfoLWCControllerTest
{
    @isTest
    public static void getVehicleDetailsByCaseTest()
    {
        Case CID=new Case(status='New',origin='Email');
        insert CID;
        Vehicle__c fVehicle = new Vehicle__c(Name = 'Test');
        insert fVehicle ;
        try
        {
            PMInfoLWCController.getVehicleDetailsByCase(CID.id);
        }catch(exception e)
        {
           
        }
    }
}
Sri Teja Pilla 5Sri Teja Pilla 5
Hi Andrew,

I see that for Exception throwing testcases you have written try catch block with assert in catch block. But if the method didnt throw the exception then it wont go to catch block and the testcase pass as no Exception raised and No Assert Statements failed. What to do in this case?
Md Noorzafir MondalMd Noorzafir Mondal

I have an apex helper class, for which I am getting 80% code coverage but 100% required here, will you kindly help?
APEX CLASS :


public Class Userdeactivationhelper
{   
    @future
    public static void userdeactivationmethod(id userid)
    {
        try{
            User usertodeactivate=new User(id=userid ,isactive=false);
            update usertodeactivate;
        }
        catch(Exception e){
            System.debug('Error in class Userdeactivationhelper in method userdeactivationmethod()'+e.getStackTraceString());            
        }
    }        
}

APEX TEST CLASS :

@isTest
public class UserdeactivationhelperTest {
    @isTest static public void testmethod1(){
    
    Id devRecordTypeId = Schema.SObjectType.Automation_Log__c.getRecordTypeInfosByName().get('User Deactivation').getRecordTypeId();
        List<Profile> profileList=[SELECT Id from Profile where Name='NPEARS Team'];
        User u=new User();
        
        u.FirstName='Test';
        u.LastName='User';
        u.Email='today@monday.com';
        u.ProfileId='00e0N000001VCHg';
        u.Username='username1234@username.com';
        u.Alias='abc1234';
        u.TimeZoneSidKey='Europe/Amsterdam';
        u.LocaleSidKey='en_GB';
        u.LanguageLocaleKey='en_US';
        u.IsActive=true;
        u.EmailEncodingKey='UTF-8';
        insert u;
        
        Automation_Log__c a=new Automation_Log__c();
        a.RecordTypeId=devRecordTypeId;
        a.Source__c='Portal';
        a.Status__c='Pending for Approval';
        a.User__c=u.id;
        
        insert a;
        
        Userdeactivationhelper d=new Userdeactivationhelper();
      
        Test.startTest();
        Userdeactivationhelper.userdeactivationmethod(a.User__c);
        Test.stopTest();
        }
}