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
sumit dsumit d 

test class is not covering error message in trigger helper

Hi All,
          I have a test class but it's not covering the part in which I am showing the error message. Can anyone help me with the code coverage,
and let me know what am I missing in test class.
My helper class and Test class is given below :-

public  without sharing class OpportunityLineItemTriggerHelper {
    
    public static List<OpportunityLineItem> newOpportunityLineItem = new List<OpportunityLineItem>();
    public static List<OpportunityLineItem> oldOpportunityLineItem = new List<OpportunityLineItem>();
    public static Map<Id, OpportunityLineItem> newMapOpportunityLineItem = new Map<Id, OpportunityLineItem>();
    public static Map<Id, OpportunityLineItem> oldMapOpportunityLineItem = new Map<Id, OpportunityLineItem>(); 
     public static void validateServiceAgreementProduct(){
        
        Map<Id, Product2> mapProductIdToProduct = new Map<Id, Product2>(
                                                                        [ SELECT Id, Name, Family
                                                                           FROM Product2 
                                                                           WHERE Family LIKE 'SA - %'
                                                                           OR Family LIKE 'Service - %'
                                                                        ]
                                                                        );
        Set<Id> parentOppIds = new Set<Id>();
        Set<Id> serviceProductIds = new Set<Id>();
        List<OpportunityLineItem> serviceProductLines = new List<OpportunityLineItem>();
        for( OpportunityLineItem oppLine : newOpportunityLineItem ){
            if( mapProductIdToProduct.containsKey( oppLine.Product2Id ) ){
                parentOppIds.add( oppLine.opportunityId );
                serviceProductLines.add( oppLine );
                serviceProductIds.add( oppLine.Product2Id );
            }
        }
        
        Map<Id, Opportunity> oppMap = new Map<Id, Opportunity>( [ SELECT Id, Name, 
                                                                 ( SELECT Id, Name, Product2Id 
                                                                   FROM OpportunityLineItems 
                                                                   Where Product2Id not in :serviceProductIds
                                                                 )
                                                                 FROM Opportunity
                                                                 WHERE Id IN: parentOppIds ] 
                                                               );
                                                               
        Map<Id, Set<Id>> mapOppIdToHardwareProductIds = new Map<Id, Set<Id>>();
        for( Opportunity opp : oppMap.values() ) {
            Set<Id> setHarwareProductIds = new Set<Id>();
            for( OpportunityLineItem opli : opp.OpportunityLineItems ) {
                setHarwareProductIds.add( opli.Product2Id );
            }
            mapOppIdToHardwareProductIds.put( opp.Id, setHarwareProductIds );
        }
        
        Map<Id, Set<Id>> mapServicesProductIDToHardwareProductIds = new Map<Id, Set<Id>>();
        for( SA_Junction__c sJunction : [ SELECT Id, Hardware_Product__c, 
                                          Services_Product__c 
                                          FROM SA_Junction__c 
                                          Where Services_Product__c in :serviceProductIds
                                         ] 
                                         ){
            Set<Id> hardwareProductIds = mapServicesProductIDToHardwareProductIds.get( sJunction.Services_Product__c );
            hardwareProductIds = hardwareProductIds == null ? new Set<Id>() : hardwareProductIds;
            hardwareProductIds.add( sJunction.Hardware_Product__c );                             
            mapServicesProductIDToHardwareProductIds.put( sJunction.Services_Product__c, hardwareProductIds );                                        
        }
        
        for( OpportunityLineItem oppLine : serviceProductLines ){
            Set<Id> actualHardwareProductIdsOnOpp = mapOppIdToHardwareProductIds.get( oppLine.OpportunityId );
            Set<Id> expectedHardwareProductIds = mapServicesProductIDToHardwareProductIds.get( oppLine.Product2Id );
            if( expectedHardwareProductIds != null && expectedHardwareProductIds.size() > 0 
                && actualHardwareProductIdsOnOpp != null && actualHardwareProductIdsOnOpp.size() > 0 ) {
                Boolean hasExpectedHardware = false;
                for( Id hardwareProdId : actualHardwareProductIdsOnOpp ) {
                    if( expectedHardwareProductIds.contains( hardwareProdId )) {
                        hasExpectedHardware = true;
                        break;  
                    }
                }
                if( !hasExpectedHardware ) {  
                    oppLine.addError('You need to select the correct agreement based on hardware products.'); 
                }
            }
        }

    }
}
how to cover bold part?
Test class for trigger helper:-
@istest

private class Trigger_OpportunityLineItemTest {
static testmethod void validateServiceAgreementProductTest(){
        Account accTest = new Account( Name = 'Test Account' );
        insert accTest;
        
        Opportunity oppTest = new Opportunity( Name = 'Test Opportunity',
                                              StageName = 'Working',
                                              CloseDate = System.today(),
                                              AccountId = accTest.Id );
        insert oppTest;
        
        Product2 prod = new Product2( Name ='EV - PM1H0000BD',
                                     isActive = TRUE,
                                     Family = ' Printers' );
        insert prod;
        
        PricebookEntry pbe = new PricebookEntry( UnitPrice = 10,
                                                Product2Id = prod.Id,
                                                Pricebook2Id = Test.getStandardPricebookId(),
                                                isActive = TRUE, 
                                                UseStandardPrice = FALSE );
        insert pbe;
        
        
        Product2 prod1 = new Product2( Name ='Service Agreement - Full - Primacy Dual',
                                      isActive = TRUE,
                                      Family = ' SA - Hardware' );
        insert prod1;
        
        PricebookEntry pb = new PricebookEntry( UnitPrice = 20,
                                               Product2Id = prod1.Id,
                                               Pricebook2Id = Test.getStandardPricebookId(),
                                               isActive = TRUE, 
                                               UseStandardPrice = FALSE );
        insert pb;
        
        OpportunityLineItem oppLine = new OpportunityLineItem( OpportunityId = oppTest.Id,
                                                              Quantity = 2,
                                                              UnitPrice = 10,
                                                              Product2Id = prod.id,
                                                              PriceBookEntryId = pbe.Id
                                                             );
        insert oppLine;
        
        OpportunityLineItem oppLine1 = new OpportunityLineItem( OpportunityId = oppTest.Id,
                                                               Quantity = 2,
                                                               UnitPrice = 10,
                                                               Product2Id = prod1.id,
                                                               PriceBookEntryId = pb.Id
                                                              );
        insert oppLine1;
        
        OpportunityLineItem Oli = [select Name,Product2.Name
                                   from OpportunityLineItem 
                                   where OpportunityId =: oppTest.Id AND Product2Id =: prod.id ];
        System.assertEquals('EV - PM1H0000BD', Oli.Product2.Name );
    }
    
    static testmethod void validateServiceAgreementProductTestError(){
        Account accTest = new Account( Name = 'Test Account' );
        insert accTest;
        
        Opportunity oppTest = new Opportunity( Name = 'Test Opportunity',
                                              StageName = 'Working',
                                              CloseDate = System.today(),
                                              AccountId = accTest.Id );
        insert oppTest;
        
        Product2 prod = new Product2( Name ='EV - PM1H0000BD',
                                     isActive = TRUE,
                                     Family = 'Printers' );
        insert prod;
        
        PricebookEntry pbe = new PricebookEntry( UnitPrice = 10,
                                                Product2Id = prod.Id,
                                                Pricebook2Id = Test.getStandardPricebookId(),
                                                isActive = TRUE, 
                                                UseStandardPrice = FALSE );
        insert pbe;
        
        Product2 prod1 = new Product2( Name ='Service Agreement - Full - SD260',
                                      isActive = TRUE,
                                      Family = 'SA - Hardware' );
        insert prod1;
        
        PricebookEntry pb = new PricebookEntry( UnitPrice = 20,
                                               Product2Id = prod1.Id,
                                               Pricebook2Id = Test.getStandardPricebookId(),
                                               isActive = TRUE, 
                                               UseStandardPrice = FALSE );
        insert pb;
        
        SA_Junction__c SA = new SA_Junction__c();
        SA.Hardware_Product__c =  prod.id;
        SA.Services_Product__c =  prod1.id;
        insert SA;
        
        OpportunityLineItem oppLine = new OpportunityLineItem( OpportunityId = oppTest.Id,
                                                              Quantity = 2,
                                                              UnitPrice = 10,
                                                              Product2Id = prod.id,
                                                              PriceBookEntryId = pbe.Id
                                                             );
        insert oppLine;
        
        OpportunityLineItem oppLine1 = new OpportunityLineItem( OpportunityId = oppTest.Id,
                                                               Quantity = 2,
                                                               UnitPrice = 10,
                                                               Product2Id = prod1.id,
                                                               PriceBookEntryId = pbe.Id
                                                              );
         insert oppLine1;
        try{
             OpportunityLineItem Oli = [select Name,Product2.Name
                                   from OpportunityLineItem 
                                   where OpportunityId =: oppTest.Id AND Product2Id =: prod1.id ];
           System.assertEquals('Service Agreement - Full - SD260',oppLine1.Product2.Name);
             
        }
        catch(Exception e) {
            Boolean expectedExceptionThrown =  e.getMessage().contains('You need to select the correct agreement based on hardware products.') ? true : false;
            System.AssertEquals(expectedExceptionThrown, false);
            
        }
        
    }
}
PRAKASH JADA 13PRAKASH JADA 13

serviceProductLines is empty that is why it is not covering that part please work on your test data. the best way to debug with test class is adding system.asserts, system.assertNotEquals, System.assertEquals. by this, you will know that your test data is correct for the scenario that you are testing.

sumit dsumit d
Hi Prakash,
       Thanks for replying, I have updated the test class but still not able to cover the  oppLine.addError('You need to select the correct agreement based on hardware products.'), Can you tell me what I am missing in test class?
My updated test class is given below:-

@istest
private class Trigger_OpportunityLineItemTest {
     static testmethod void validateServiceAgreementProductTest(){
        Account accTest = new Account( Name = 'Test Account' );
        insert accTest;
        
        Opportunity oppTest = new Opportunity( Name = 'Test Opportunity',
                                              StageName = 'Working',
                                              CloseDate = System.today(),
                                              AccountId = accTest.Id );
        insert oppTest;
        
        Product2 prod = new Product2( Name ='EV - PM1H0000BD',
                                     isActive = TRUE,
                                     Family = ' Printers' );
        insert prod;
        
        PricebookEntry pbe = new PricebookEntry( UnitPrice = 10,
                                                Product2Id = prod.Id,
                                                Pricebook2Id = Test.getStandardPricebookId(),
                                                isActive = TRUE, 
                                                UseStandardPrice = FALSE );
        insert pbe;
        
        
        Product2 prod1 = new Product2( Name ='Service Agreement - Full - Primacy Dual',
                                      isActive = TRUE,
                                      Family = ' SA - Hardware' );
        insert prod1;
        
        PricebookEntry pb = new PricebookEntry( UnitPrice = 20,
                                               Product2Id = prod1.Id,
                                               Pricebook2Id = Test.getStandardPricebookId(),
                                               isActive = TRUE, 
                                               UseStandardPrice = FALSE );
        insert pb;
        
        SA_Junction__c SA = new SA_Junction__c();
        SA.Hardware_Product__c =  prod.id;
        SA.Services_Product__c =  prod1.id;
        insert SA;
        
        OpportunityLineItem oppLine = new OpportunityLineItem( OpportunityId = oppTest.Id,
                                                              Quantity = 2,
                                                              UnitPrice = 10,
                                                              Product2Id = prod.id,
                                                              PriceBookEntryId = pbe.Id
                                                             );
        insert oppLine;
        
        OpportunityLineItem oppLine1 = new OpportunityLineItem( OpportunityId = oppTest.Id,
                                                               Quantity = 2,
                                                               UnitPrice = 10,
                                                               Product2Id = prod1.id,
                                                               PriceBookEntryId = pb.Id
                                                              );
        insert oppLine1;
        
        OpportunityLineItem Oli = [select Name,Product2.Name
                                   from OpportunityLineItem 
                                   where OpportunityId =: oppTest.Id AND Product2Id =: prod.id ];
        System.assertEquals('EV - PM1H0000BD', Oli.Product2.Name );
    }
    
    static testmethod void validateServiceAgreementProductTestError(){
        Account accTest = new Account( Name = 'Test Account' );
        insert accTest;
        
        Opportunity oppTest = new Opportunity( Name = 'Test Opportunity',
                                              StageName = 'Working',
                                              CloseDate = System.today(),
                                              AccountId = accTest.Id );
        insert oppTest;
        
         Product2 prod = new Product2( Name ='EV - PM1H0000BD',
                                     isActive = TRUE,
                                     Family = 'Printers' );
        insert prod;
        
        Product2 prod1 = new Product2( Name ='Service Agreement - Full - SD260',
                                      isActive = TRUE,
                                      Family = 'SA - Hardware' );
        insert prod1;
        
         Product2 prod2 = new Product2( Name ='Service Agreement - Full - Primacy Dual',
                                      isActive = TRUE,
                                      Family = 'SA - Hardware' );
        insert prod2;
        
        SA_Junction__c SA = new SA_Junction__c();
        SA.Hardware_Product__c =  prod.id;
        SA.Services_Product__c =  prod2.id;
        insert SA;
        
        
        PricebookEntry pbe = new PricebookEntry( UnitPrice = 10,
                                                Product2Id = prod.Id,
                                                Pricebook2Id = Test.getStandardPricebookId(),
                                                isActive = TRUE, 
                                                UseStandardPrice = FALSE );
        insert pbe;
        
        OpportunityLineItem oppLine = new OpportunityLineItem( OpportunityId = oppTest.Id,
                                                              Quantity = 2,
                                                              UnitPrice = 10,
                                                              Product2Id = prod.id,
                                                              PriceBookEntryId = pbe.Id
                                                             );
        insert oppLine;
        
        
        
        PricebookEntry pb = new PricebookEntry( UnitPrice = 20,
                                               Product2Id = prod1.Id,
                                               Pricebook2Id = Test.getStandardPricebookId(),
                                               isActive = TRUE, 
                                               UseStandardPrice = FALSE );
        insert pb;
        
        OpportunityLineItem oppLine1 = new OpportunityLineItem( OpportunityId = oppTest.Id,
                                                               Quantity = 2,
                                                               UnitPrice = 10,
                                                               Product2Id = prod1.id,
                                                               PriceBookEntryId = pbe.Id
                                                              );
         insert oppLine1;
        test.startTest();
        Boolean exceptionThrown = false;
        try{
            
             OpportunityLineItem Oli = [select Name,Product2.Name
                                   from OpportunityLineItem 
                                   where OpportunityId =: oppTest.Id AND Product2Id =: prod1.id ];
           System.assertEquals('Service Agreement - Full - SD260',oppLine1.Product2.Name);
             
        }
        catch(Exception e) {
            exceptionThrown = true;
            Boolean expectedExceptionThrown =  e.getMessage().contains('You need to select the correct agreement based on hardware products.') ? true : false;
            //System.AssertEquals(true, expectedExceptionThrown, e.getMessage());
         }
        System.assertEquals(true, exceptionThrown, 'No exception was thrown');
          test.stopTest();        
    }
}
PRAKASH JADA 13PRAKASH JADA 13
You don't need this convert this code to the below code
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
    try{
            
             OpportunityLineItem Oli = [select Name,Product2.Name
                                   from OpportunityLineItem 
                                   where OpportunityId =: oppTest.Id AND Product2Id =: prod1.id ];
           System.assertEquals('Service Agreement - Full - SD260',oppLine1.Product2.Name);
             
        }
        catch(Exception e) {
            exceptionThrown = true;
            Boolean expectedExceptionThrown =  e.getMessage().contains('You need to select the correct agreement based on hardware products.') ? true : false;
            //System.AssertEquals(true, expectedExceptionThrown, e.getMessage());
         }

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
       
// change this sample code to your Opportunity line item that where you are trying to cover the catch block right.

Create the data for the failure case where it goes to catch block add that insert variable to the below code
Database.DeleteResult[] results = Database.delete(oppLine1, false);
        Test.stopTest();
        // Verify for each record.
        for(Database.DeleteResult dr : results) {
            System.assert(!dr.isSuccess());
            System.assert(dr.getErrors().size() > 0);
            System.assertEquals('You need to select the correct agreement based on hardware products.',
                                dr.getErrors()[0].getMessage());
        }

 
sumit dsumit d
Hi prakash,
I did like given below:-
@istest
private class Trigger_OpportunityLineItemTest {
    
    static testmethod void validateServiceAgreementProductTest(){
        Account accTest = new Account( Name = 'Test Account' );
        insert accTest;
        
        Opportunity oppTest = new Opportunity( Name = 'Test Opportunity',
                                              StageName = 'Working',
                                              CloseDate = System.today(),
                                              AccountId = accTest.Id );
        insert oppTest;
        
        Product2 prod = new Product2( Name ='EV - PM1H0000BD',
                                     isActive = TRUE,
                                     Family = ' Printers' );
        insert prod;
        
        PricebookEntry pbe = new PricebookEntry( UnitPrice = 10,
                                                Product2Id = prod.Id,
                                                Pricebook2Id = Test.getStandardPricebookId(),
                                                isActive = TRUE, 
                                                UseStandardPrice = FALSE );
        insert pbe;
        
        
        Product2 prod1 = new Product2( Name ='Service Agreement - Full - Primacy Dual',
                                      isActive = TRUE,
                                      Family = ' SA - Hardware' );
        insert prod1;
        
        PricebookEntry pb = new PricebookEntry( UnitPrice = 20,
                                               Product2Id = prod1.Id,
                                               Pricebook2Id = Test.getStandardPricebookId(),
                                               isActive = TRUE, 
                                               UseStandardPrice = FALSE );
        insert pb;
        
        SA_Junction__c SA = new SA_Junction__c();
        SA.Hardware_Product__c =  prod.id;
        SA.Services_Product__c =  prod1.id;
        insert SA;
        
        OpportunityLineItem oppLine = new OpportunityLineItem( OpportunityId = oppTest.Id,
                                                              Quantity = 2,
                                                              UnitPrice = 10,
                                                              Product2Id = prod.id,
                                                              PriceBookEntryId = pbe.Id
                                                             );
        insert oppLine;
        
        OpportunityLineItem oppLine1 = new OpportunityLineItem( OpportunityId = oppTest.Id,
                                                               Quantity = 2,
                                                               UnitPrice = 10,
                                                               Product2Id = prod1.id,
                                                               PriceBookEntryId = pb.Id
                                                              );
        insert oppLine1;
        
        OpportunityLineItem Oli = [select Name,Product2.Name
                                   from OpportunityLineItem 
                                   where OpportunityId =: oppTest.Id AND Product2Id =: prod.id ];
        
        OpportunityLineItem Olit = [select Name,Product2.Name
                                    from OpportunityLineItem 
                                    where OpportunityId =: oppTest.Id AND Product2Id =: prod1.id ];
        System.assertEquals('EV - PM1H0000BD', Oli.Product2.Name );
        System.assertEquals('Service Agreement - Full - Primacy Dual', Olit.Product2.Name );
        
    }
    
    static testmethod void validateServiceAgreementProductTestError(){
        Account accTest = new Account( Name = 'Test Account' );
        insert accTest;
        
        Opportunity oppTest = new Opportunity( Name = 'Test Opportunity',
                                              StageName = 'Working',
                                              CloseDate = System.today(),
                                              AccountId = accTest.Id );
        insert oppTest;
        
        Product2 prod = new Product2( Name ='EV - PM1H0000BD',
                                     isActive = TRUE,
                                     Family = 'Printers' );
        insert prod;
        
        PricebookEntry pbe = new PricebookEntry( UnitPrice = 10,
                                                Product2Id = prod.Id,
                                                Pricebook2Id = Test.getStandardPricebookId(),
                                                isActive = TRUE, 
                                                UseStandardPrice = FALSE );
        insert pbe;
        
        Product2 prod1 = new Product2( Name ='Service Agreement - Limited - ZXP Series 3',
                                      isActive = TRUE,
                                      Family = 'SA - Hardware' );
        insert prod1;
        
        PricebookEntry pb = new PricebookEntry( UnitPrice = 20,
                                               Product2Id = prod1.Id,
                                               Pricebook2Id = Test.getStandardPricebookId(),
                                               isActive = TRUE, 
                                               UseStandardPrice = FALSE );
        insert pb;
        
        Product2 prod2 = new Product2( Name ='Service Agreement - Full - Primacy Dual',
                                      isActive = TRUE,
                                      Family = 'SA - Hardware' );
        insert prod2;
        
        PricebookEntry p = new PricebookEntry( UnitPrice = 20,
                                              Product2Id = prod2.Id,
                                              Pricebook2Id = Test.getStandardPricebookId(),
                                              isActive = TRUE, 
                                              UseStandardPrice = FALSE );
        insert p;
        
        SA_Junction__c SA = new SA_Junction__c();
        SA.Hardware_Product__c =  prod.id;
        SA.Services_Product__c =  prod2.id;
        insert SA;
        
        OpportunityLineItem oppLine = new OpportunityLineItem( OpportunityId = oppTest.Id,
                                                              Quantity = 2,
                                                              UnitPrice = 10,
                                                              Product2Id = prod.id,
                                                              PriceBookEntryId = pbe.Id
                                                             );
        //insert oppLine;
        
        OpportunityLineItem oppLine1 = new OpportunityLineItem( OpportunityId = oppTest.Id,
                                                               Quantity = 2,
                                                               UnitPrice = 10,
                                                               Product2Id = prod1.id,
                                                               PriceBookEntryId = pb.Id
                                                              );
        test.startTest();
        List<OpportunityLineItem> oliList = new List<OpportunityLineItem>();
        oliList.add(oppLine);
        oliList.add(oppLine1);
        Database.SaveResult[] results = Database.insert(oliList, false);
        test.stopTest();   
        
        if(oliList.Size() > 0){
            for(Database.SaveResult dr : results) {
            System.assert(!dr.isSuccess());
            System.assert(dr.getErrors().size() > 0);
            System.assertEquals('You need to select the correct agreement based on hardware products.',
                                dr.getErrors()[0].getMessage());
            //System.assert(e.getMessage().contains('You need to select the correct agreement based on hardware products.'),e.getMessage());
        }
        }
      }
}
Still not able to cover it?
Can you tell me what i missed?
PRAKASH JADA 13PRAKASH JADA 13
Hi,


Do you know that oliList won't be created and when you to try to inset it should throw an error?


Create test record that fall into

for( Id hardwareProdId : actualHardwareProductIdsOnOpp ) {
                    if( expectedHardwareProductIds.contains( hardwareProdId )) {
                        hasExpectedHardware = true;
                        break;  
                    }
                }
                if( !hasExpectedHardware ) {    ===> this condition 
                    oppLine.addError('You need to select the correct agreement based on hardware products.'); 
                }
            }
        }


and place that test record insert in 


for(Database.SaveResult dr : results) {
            System.assert(!dr.isSuccess());
            System.assert(dr.getErrors().size() > 0);
            System.assertEquals('You need to select the correct agreement based on hardware products.',
                                dr.getErrors()[0].getMessage());
            //System.assert(e.getMessage().contains('You need to select the correct agreement based on hardware products.'),e.getMessage());
        }
        }


Basically what you are missing is the negative case of testing. If the line has to cover you need to create a negative test case.