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
Jasril Dane CaliwagJasril Dane Caliwag 

hello! can anyone help me to cover the catch method in my class by the test class? the catch method is not covered by the test class.

here is my code:
public class AddPriceModalController {
    @AuraEnabled
    public static List<String> getRegionValues() {
        List<String> lstGeography = new List<String>(); //new list for holding all of the picklist options
        
        Schema.DescribeFieldResult fieldResult = PriceDetail__c.Geography__c.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        
        for( Schema.PicklistEntry f : ple)
        {
            lstGeography.add(f.getValue());
        }
        
        return lstGeography;
    }
    
    @AuraEnabled
    public static List<String> getDeliveryMethodValues() {
        List<String> lstSourceOfSupply = new List<String>(); //new list for holding all of the picklist options
        
        Schema.DescribeFieldResult fieldResult = PriceDetail__c.Source_of_Supply__c.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        
        for( Schema.PicklistEntry f : ple)
        {
            lstSourceOfSupply.add(f.getLabel() + '---' + f.getValue());            
        }
        
        return lstSourceOfSupply;
    }
    //Method to Save the Price Detail Change Request
    @AuraEnabled
    public static String savePriceDetails(Id PDID,PriceDetail__c newPriceDetails) {
        system.debug('savePriceDetails');
        system.debug('newPriceDetails'+newPriceDetails);
        Decimal invoiceCost = 0;
        Decimal netCost = 0;
        Decimal netProfit = 0;
        Decimal retailPrice = 0;
        string resultId;
        //Webservice Call to SAP to get the InvoiceCost and NetCost
        /*invoiceCost = PriceDetailsWebService.getInvoiceCost(PDID);
netCost = PriceDetailsWebService.getNetCost(PDID);*/
        
        String PDSOQL = SObjectUtil.getSOQLStringFullFields(PriceDetail__c.getSObjectType())
            +' WHERE ' + ' Id = :PDID LIMIT 1';
        //List<PriceDetail__c> listPD = Database.query(PDSOQL);
        PriceDetail__c PDRec;
        try{
            PDRec = Database.query(PDSOQL);   
        }catch(Exception e){
            ApplicationLogUtility.logError('SubmitActionController', 'getParentId', e, e.getMessage(), '', 0);
            ApplicationLogUtility.commitLog();
            PDRec = null; 
        }   
        if(PDRec!=null){
            PriceDetail__c clonedPD = PDRec.clone(false, true, false, false);
            clonedPD.InvoiceCost__c = invoiceCost;
            clonedPD.NetCost__c = netCost;
            clonedPD.ClonedFrom__c = PDRec.Id;
            clonedPD.Status__c = Label.Draft;
            clonedPD.RecordTypeId = Schema.SObjectType.PriceDetail__c.getRecordTypeInfosByName().get(Label.PriceDetail_Submit).getRecordTypeId();
            Schema.DescribeSObjectResult objResult = PriceDetail__c.sObjectType.getDescribe();
            for(string apiName : objResult.fields.getMap().keySet()){
                String feildName = apiName;
                if(feildName.endsWith('__c')){
                    if((clonedPD.get(apiName) != newPriceDetails.get(apiName)) && (feildName!= 'ClonedFrom__c')){
                        system.debug('feildName***'+feildName);
                        clonedPD.put(apiName, newPriceDetails.get(apiName));
                    }
                }
            }
            system.debug('clonedPD**'+clonedPD);
            if(clonedPD!=null){
                insert clonedPD;    
            }
            
            resultId = Id.valueOf(clonedPD.Id);
            system.debug('resultId'+resultId);
            
        }
        
        return resultId;
    }
    
    //Method to get the exsisting data from the record
    @AuraEnabled
    public static PriceDetail__c getPriceDetails(Id recordId) {
        system.debug('recordId**'+recordId);
        PriceDetail__c pdRecord = (PriceDetail__c) SObjectUtil.getFullSObject(PriceDetail__c.getSObjectType(), recordId);
        return pdRecord;
        
    }
    
    
    
    
}

here is the test class:
@isTest
private class AddPriceModalControllerTest {
    
    @testSetup 
    static void createData() {
        
        TriggerApexSwitch__c apexSwitchNutritionalDetail = TestDataFactory.createApexSwitchTestData(System.Label.NutritionalDetail);
        insert apexSwitchNutritionalDetail;
        
        //Custom Settings - Insert Record for Account
        TriggerApexSwitch__c apexSwitchAccount = TestDataFactory.createApexSwitchTestData(System.Label.Account);
        insert apexSwitchAccount;
        
                TriggerApexSwitch__c apexSwitchUser = TestDataFactory.createApexSwitchTestData(System.Label.User);
        insert apexSwitchUser;
        
        //Custom Settings - Insert Record for SupplierProductArticle    
        TriggerApexSwitch__c apexSwitchSupplierProductArticle     = TestDataFactory.createApexSwitchTestData(System.Label.SupplierProductArticle);
        insert apexSwitchSupplierProductArticle    ;
          
        //Custom Settings - Insert Record for Price Detail    
        TriggerApexSwitch__c apexSwitchPriceDetail     = TestDataFactory.createApexSwitchTestData(System.Label.PriceDetail);
        insert apexSwitchPriceDetail;
          
        //Custom Settings - Insert Record for Case    
        TriggerApexSwitch__c apexSwitchCase = TestDataFactory.createApexSwitchTestData(System.Label.Case);
        insert apexSwitchCase;  
      
        //Custom Settings - Insert Record for GPA    
        TriggerApexSwitch__c apexSwitchGPA = TestDataFactory.createApexSwitchTestData('GlobalProductArticle');
        insert apexSwitchGPA;  
        
        //Custom Settings - Insert Record for Pack Detail    
        TriggerApexSwitch__c apexSwitchPD = TestDataFactory.createApexSwitchTestData('PackDetail');
        insert apexSwitchPD;  
        
        
        //Custom Settings - Insert Record for Retail price    
        TriggerApexSwitch__c apexSwitchRetail = TestDataFactory.createApexSwitchTestData(System.Label.RetailPrice);
        insert apexSwitchRetail;  
        
        //Custom Settings - Insert Record for GTIN    
        TriggerApexSwitch__c apexSwitchGTIN = TestDataFactory.createApexSwitchTestData(System.Label.GlobalTradeItemNumber);
        insert apexSwitchGTIN; 
       
        
        String ArticleEnrichment = Schema.SObjectType.SupplierProductArticle__c.getRecordTypeInfosByName().get('Article Enrichment').getRecordTypeId();
        
        //Create Test data for Account 
        Account accountRec = TestDataFactory.createAccountTestData(1);       
        insert accountRec;                

        //Custom Settings - Insert Record for Contact    
        TriggerApexSwitch__c apexSwitchContact = TestDataFactory.createApexSwitchTestData(System.Label.Contact);
        insert apexSwitchContact;
        
        //Custom Settings - Insert Record for AccountContactRelation    
        TriggerApexSwitch__c apexSwitchAccountContactRelation = TestDataFactory.createApexSwitchTestData(System.Label.AccountContactRelation);
        insert apexSwitchAccountContactRelation;
        
        //Create Test Data for Contact
        Contact contactRec = TestDataFactory.createContactTestData(1, accountRec.Id);
        insert contactRec;
        
        Global_Product_Article__c gpTest = new Global_Product_Article__c();
        gpTest.Article_Hierarchy_Sub_Category_Name__c = 'Test';
        gpTest.Wow_Article_Number__c = NULL;
        insert gpTest;
        
        SupplierProductArticle__c[] spaList = new List<SupplierProductArticle__c>();
        SupplierProductArticle__c spaTest = new SupplierProductArticle__c();
        spaTest.Account__c = accountRec.Id;
        spaTest.Global_Product_Article__c = gpTest.Id;
        spaTest.RecordTypeId = ArticleEnrichment;
        spaTest.Sub_Status__c = 'Awaiting Documents';
        insert spaTest;
        
        Retail_Price__c[] rpList = new List<Retail_Price__c>();
        Retail_Price__c rpTest = new Retail_Price__c();
        rpTest.SupplierProductArticle__c = spaTest.Id;
        rpTest.Number_of_Units__c = 453;
        rpTest.GTIN__c = '8956353';
        rpList.add(rpTest);
        insert rpList;
        
        PackDetail__c pdTest = TestDataFactory.createPackDetails(gpTest.Id);
        pdTest.GTIN__c = '34802';
        pdTest.NumberOfUnits__c = 34;
        pdTest.Orderable_Unit__c = 'Yes';
        insert pdTest;
        
        PriceDetail__c priceRec = new PriceDetail__c();
        priceRec.SupplierProductArticle__c = spaTest.Id;
        priceRec.BonusStockQualifyingQty__c = 89;
        
        insert priceRec;
        
        priceRec.Orderable_GTIN__c = '34802';
        update priceRec;

        //PDRec.clone(false, true, false, false);
        PriceDetail__c PDRec = new PriceDetail__c();
        PDRec.InvoiceCost__c = 888;
        PDRec.NetCost__c = 466;
        PDRec.Status__c = Label.Draft;
        PDRec.SupplierProductArticle__c = spaTest.Id;
        PDRec.RecordTypeId = Schema.SObjectType.PriceDetail__c.getRecordTypeInfosByName().get(Label.PriceDetail_Submit).getRecordTypeId();
        insert PDRec;
        
        PriceDetail__c pD = PDRec.clone(false, true, false, false);
            pD.InvoiceCost__c = 999;
            pD.NetCost__c = 577;
            pD.Status__c = Label.Draft;
            pD.SupplierProductArticle__c = spaTest.Id;
            pD.RecordTypeId = Schema.SObjectType.PriceDetail__c.getRecordTypeInfosByName().get(Label.PriceDetail_Submit).getRecordTypeId();
            insert pD;
    }
    
    @isTest static void getRegionValuesTest(){
        System.assertNotEquals(null, AddPriceModalController.getRegionValues());
    }
    
    @isTest static void getDeliveryMethodValuesTest(){
        System.assertNotEquals(null, AddPriceModalController.getDeliveryMethodValues());
    }
    
    @isTest static void savePriceDetailsTest(){
        //List<PriceDetail__c> pD = [Select Id, InvoiceCost__c, NetCost__c, RecordTypeId, Geography__c  FROM PriceDetail__c];
      String PDSOQL = SObjectUtil.getSOQLStringFullFields(PriceDetail__c.getSObjectType())
            +' LIMIT 1';
        PriceDetail__c pD = Database.query(PDSOQL); 
        AddPriceModalController.savePriceDetails(pD.Id, pD);
    }
    
    @isTest static void getgetPriceDetailsTest(){
        List<PriceDetail__c> pD = [Select Id, InvoiceCost__c, NetCost__c, RecordTypeId  FROM PriceDetail__c];
        System.assertNotEquals(null, AddPriceModalController.getPriceDetails(pD[0].Id));
    }
}

the catch method in my class is not covered by the test class.

here is the separate code of my try-catch method above:
   
    PriceDetail__c PDRec;
        try{
            PDRec = Database.query(PDSOQL);   
        }catch(Exception e){
            ApplicationLogUtility.logError('SubmitActionController', 'getParentId', e, e.getMessage(), '', 0);
            ApplicationLogUtility.commitLog();
            PDRec = null; 

what should i do to cover the catch method by the test class ?
Rahul.MishraRahul.Mishra
Normally we update the main class when there is need of covering the catch block, we intentionally throws an exception when test runs so that control will go to catch block, please modify your class slightly:
 
PriceDetail__c PDRec;
        try{
            PDRec = Database.query(PDSOQL); if(Test.isRunningTest())
			{
				throw new Exception();
			}  
        }catch(Exception e){
            ApplicationLogUtility.logError('SubmitActionController', 'getParentId', e, e.getMessage(), '', 0);
            ApplicationLogUtility.commitLog();
            PDRec = null;

Mark answer as best if it does solves your problem.

Thanks,
Rahul
Jasril Dane CaliwagJasril Dane Caliwag
Rahul there's an error in (throw new Exception();)
the error is : Type cannot be constructed: Exception
Rahul.MishraRahul.Mishra
Then try this:

Create an exception class:

public class applicationException extends Exception {}
Then you can throw that:
 
PriceDetail__c PDRec;
        try{
            PDRec = Database.query(PDSOQL); if(Test.isRunningTest())
			{
				throw new applicationException('You Can Thorw;);
			}  
        }catch(Exception e){
            ApplicationLogUtility.logError('SubmitActionController', 'getParentId', e, e.getMessage(), '', 0);
            ApplicationLogUtility.commitLog();
            PDRec = null;


 Let me know if it works.
 
Jasril Dane CaliwagJasril Dane Caliwag
thanks rahul