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
Haneef SHaneef S 

I am facing error for the below test class

I have created test class and facing below exception:
Error:System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, field integrity exception: []
stacktrace: 
Class.OpportunityLineItemMultiInsertTest.setData: line 54, column 1
Class.OpportunityLineItemMultiInsertTest.testInsertOLI: line 112, column 1
Apex class:
public class OpportunityLineItemMultiInsert{
    public List<OLIWrapper> wrappers {get; set;}
    public List<OpportunityLineItem> olis {get; set;}
    public Opportunity oppty {get; set;}
    public String opportunityId {get; set;}
    private Id opptyId ;
    private List<string> pbeIds;
    private List<string> pbeIdscleaned;    
 public static Integer toDelIdent {get; set;}
 public static Integer addCount {get; set;}
 private Integer nextIdent=0;   
     public Boolean showReload {get; set;}

    public OpportunityLineItemMultiInsert() {
        opportunityId = ApexPages.currentPage().getParameters().get('opptyid');
        showReload = false;
        opptyId = ApexPages.currentPage().getParameters().get('opptyid');
        pbeIds = ApexPages.currentPage().getParameters().get('ids').split(',');
        pbeIdscleaned = new List<string>();
        for (String currIdent : pbeIds ) {
            if (currIdent  != '') {
                pbeIdscleaned.add(currIdent);
            }
        }
        
        
        Map<Id, String> allPBEs = new Map<Id, String>();
        for (PricebookEntry currPBEc : [select id, Name, UnitPrice from PricebookEntry where id in :pbeIdscleaned]) {
            allPBEs.put(currPBEc.Id, currPBEc.Name);
        }
        
        wrappers=new List<OLIWrapper>();
        //nextIdent = pbeIds.size()+1;
        for (Integer idx=0; idx<pbeIdscleaned.size(); idx++)
        {
           OLIWrapper curr =   new OLIWrapper(nextIdent++);
           curr.acc.PricebookEntryId = pbeIdscleaned[idx]; //'01u24000004Nq7yAAC';
           curr.productName =  allPBEs.get(pbeIdscleaned[idx]);
           /*
           if (allPBEs.get(pbeIdscleaned[idx]).length() > 17) {
               curr.acc.zz_Previous_OLI_ID__c= allPBEs.get(pbeIdscleaned[idx]).substring(0,17);           
               
           } else {
               curr.acc.zz_Previous_OLI_ID__c= allPBEs.get(pbeIdscleaned[idx]);
           }
           */

           curr.acc.UnitPrice  = 1;

           
           curr.acc.OpportunityId = opptyId ;
           wrappers.add(curr );
        }
        
        oppty = [select id, Name from Opportunity where id = :opptyId];
        /*
        olis = [select  Id, 
                        Name,
                        Quantity,
                        TotalQtyHelper__c,
                        Duration_months__c,
                        Unit_Margin__c,
                        Units_for_Quantity__c,
                        Qty_month__c,
                        Unit_Cost__c,
                        UnitPrice,
                        TotalPrice,
                        Total_Cost__c,
                        ServiceDate,
                        Invoice_Date__c,
                        Description,
                        CurrencyIsoCode 
               from     OpportunityLineItem
               where    id in : pbeIdscleaned];
    */
        //qtyToQtyHelper();
    }
    
    public PageReference save() {

     List<OpportunityLineItem > accs=new List<OpportunityLineItem >();
      for (OLIWrapper wrap : wrappers)
      {
       wrap.acc.Quantity = wrap.acc.TotalQtyHelper__c;
       accs.add(wrap.acc);
      }
        
      System.debug('olis:' + accs);
       
      insert accs;        
      showReload = true;
      //return new PageReference('/' + opptyId);
      return null;
    }
    
    public PageReference cancel() {
        return new PageReference('/' + opptyId);
    }
    
     public class OLIWrapper
     {
      public OpportunityLineItem acc {get; private set;}
      public Integer ident {get; private set;}
      public String productName {get; set;}
       
      public OLIWrapper(Integer inIdent)
      {
       ident=inIdent;
       acc=new OpportunityLineItem (description = String.valueOf(ident));
      }
     }
    
    // TotalQtyHelper__c allows to leave the field blank where Quantity can't be blank
    private void qtyToQtyHelper() {
        for (OpportunityLineItem oli : olis) {
            oli.TotalQtyHelper__c = oli.Quantity;
        }
    }

}
Test class:
@isTest
private class OpportunityLineItemMultiInsertTest {
    private static OpportunityLineItem opptyLineItemObj;
    private static Opportunity opportunityObj;
    private static List<OpportunityLineItem> oliList ;
    
     private static void setData() {
        Account accountObj = (Account)TestDataHelper.createSObject('Account');
        accountObj.SAP_id__c='0011254999';
        accountObj.BillingCity = 'pune' ;        
        accountObj.BillingStreet = 'bhel chowk' ;        
        accountObj.BillingCountry = 'india' ;        
        accountObj.BillingPostalCode = '345210' ;
        insert accountObj;
        
        Organization__c organizationObj = (Organization__c)TestDataHelper.createSObject('Organization__c');        
        //organizationObj.Active__c = true;
        insert organizationObj; 
        
         RecordType rec = [Select id,name from recordtype where developername = 'Solution'];
        Product2 prod = new Product2(Name = 'Laptop X200', 
                                     Family = '2_PLA_BUSS', 
                                     Hierarchy_Level__c = 'SKU',
                                     ProductCode = 'abc123', 
                                     CanUseRevenueSchedule=true, 
                                     CanUseQuantitySchedule=true,
                                     recordtypeId = rec.id
                                    );
        insert prod;
      
       /* RecordType rec = [Select id,name from recordtype where developername = 'Solution'];
        Product2 prod1 = new Product2(Name = 'Laptop X200', 
                                     Family = '2_PLA_BUSS', 
                                     Hierarchy_Level__c = 'SKU',
                                     ProductCode = 'abc123', 
                                     CanUseRevenueSchedule=true, 
                                     CanUseQuantitySchedule=true,
                                      recordtypeId = rec.id
                                    );
        insert prod1;
        */
        Id pricebookId = Test.getStandardPricebookId();
        PricebookEntry standardPBE = new PricebookEntry(Pricebook2Id = pricebookId, 
                                                        Product2Id = prod.Id,   
                                                        UnitPrice = 10000, IsActive = true,UseStandardPrice = true);
         system.debug(standardPBE);
        insert standardPBE;
        
        //List<PricebookEntry> pbe = [select id, name, CurrencyIsoCode from PriceBookEntry where Pricebook2id =: 'VALUE' and Product2.Id in: VALUE.keySet() ]; 
         /*PricebookEntry standardPBE1 = new PricebookEntry(Pricebook2Id = pricebookId, 
                                                        Product2Id = prod1.Id,   
                                                        UnitPrice = 10000, IsActive = true);
        insert standardPBE1;
        */        
        opportunityObj = (Opportunity)TestDataHelper.createSObject('Opportunity');        
        opportunityObj.Accountid= accountObj.id;   
        opportunityObj.Pricebook2Id=pricebookId;        
        opportunityObj.CurrencyIsoCode=standardPBE.CurrencyIsoCode;  
        opportunityObj.Organization__c=organizationObj.id;
        insert opportunityObj;
        
         opportunityObj = (Opportunity)TestDataHelper.createSObject('Opportunity');        
        opportunityObj.Accountid= accountObj.id;   
        opportunityObj.Pricebook2Id=pricebookId;        
        //opportunityObj.CurrencyIsoCode=standardPBE1.CurrencyIsoCode;   
        opportunityObj.Organization__c=organizationObj.id;
        insert opportunityObj;
        
        OpportunityTeamMember otm=new OpportunityTeamMember();
        otm.userid=userinfo.getuserid();
        otm.TeamMemberRole='High Level';
        otm.opportunityid=opportunityObj.id;
        otm.Lead_Type__c='Test Lead';
        
        insert otm;
         
        
        oliList = new List<OpportunityLineItem>();
        for(integer i = 0; i<= 5; i++) {
            opptyLineItemObj = new OpportunityLineItem();        
            opptyLineItemObj.Quantity=1;
            opptyLineItemObj.Oppty_Team_Members__c ='['+ otm.User.Name +','+ otm.Lead_Type__c +']';
            opptyLineItemObj.TotalPrice=500;
            opptyLineItemObj.Delivery_Date_Start__c = system.today().addDays(5);
            opptyLineItemObj.Delivery_Date_Last__c = system.today().addDays(7);
            opptyLineItemObj.Revenue_Date_Last__c = system.today().addDays(5);
            opptyLineItemObj.Revenue_Date_Start__c = system.today().addDays(7);
            opptyLineItemObj.Quote_Package_Name__c = 'packageName';
            //opptyLineItemObj.HasSchedule = true;
            opptyLineItemObj.PricebookEntryId=standardPBE.id; 
           // opptyLineItemObj.PricebookEntryId=standardPBE1.id; 
            opptyLineItemObj.opportunityid=opportunityObj.id;
            opptyLineItemObj.ServiceDate = system.today().addDays(5);
            opptyLineItemObj.Invoice_Date__c = system.today().addDays(5);
            
            oliList.add(opptyLineItemObj);
        }
        insert oliList;
    }
    
    
    
     static testmethod void testInsertOLI() {
        
        setData();
        /*
        List<OpportunityLineItem> olis = new List<OpportunityLineItem>();
        List<PricebookEntry> pbe = new List<PricebookEntry>();
        Opportunity oppty = TestDataHelper.createOpptyWithOfferings('Product',olis);
 */ 
        
        string oliIds = '';
       
        for (OpportunityLineItem oli : oliList) {
            oliIds = oliIds + ',' + oli.id;
        }
        oliIds = oliIds.substring(1);
        
        Test.startTest();
        ApexPages.currentPage().getParameters().put('opptyid',opportunityObj.id);
        ApexPages.currentPage().getParameters().put('ids',oliIds);
        
        OpportunityLineItemMultiInsert ctr = new OpportunityLineItemMultiInsert();
        ctr.save();
        ctr.cancel();
        //ctr.qtyToQtyHelper();
        ctr.olis = oliList;
        Boolean testValue;
        if(ctr != null){
        testValue = true;
        }
        System.assert(testValue); 
    }

}

Any help will be appreciated
Thanks,
Haneef
Steven NsubugaSteven Nsubuga
Try removing the UseStandardPrice = true from pricebookentry 
@isTest
private class OpportunityLineItemMultiInsertTest {
    private static OpportunityLineItem opptyLineItemObj;
    private static Opportunity opportunityObj;
    private static List<OpportunityLineItem> oliList ;
    
     private static void setData() {
        Account accountObj = (Account)TestDataHelper.createSObject('Account');
        accountObj.SAP_id__c='0011254999';
        accountObj.BillingCity = 'pune' ;        
        accountObj.BillingStreet = 'bhel chowk' ;        
        accountObj.BillingCountry = 'india' ;        
        accountObj.BillingPostalCode = '345210' ;
        insert accountObj;
        
        Organization__c organizationObj = (Organization__c)TestDataHelper.createSObject('Organization__c');        
        //organizationObj.Active__c = true;
        insert organizationObj; 
        
         RecordType rec = [Select id,name from recordtype where developername = 'Solution'];
        Product2 prod = new Product2(Name = 'Laptop X200', 
                                     Family = '2_PLA_BUSS', 
                                     Hierarchy_Level__c = 'SKU',
                                     ProductCode = 'abc123', 
                                     CanUseRevenueSchedule=true, 
                                     CanUseQuantitySchedule=true,
                                     recordtypeId = rec.id
                                    );
        insert prod;
      
       /* RecordType rec = [Select id,name from recordtype where developername = 'Solution'];
        Product2 prod1 = new Product2(Name = 'Laptop X200', 
                                     Family = '2_PLA_BUSS', 
                                     Hierarchy_Level__c = 'SKU',
                                     ProductCode = 'abc123', 
                                     CanUseRevenueSchedule=true, 
                                     CanUseQuantitySchedule=true,
                                      recordtypeId = rec.id
                                    );
        insert prod1;
        */
        Id pricebookId = Test.getStandardPricebookId();
        PricebookEntry standardPBE = new PricebookEntry(Pricebook2Id = pricebookId, 
                                                        Product2Id = prod.Id,   
                                                        UnitPrice = 10000, IsActive = true);
         system.debug(standardPBE);
        insert standardPBE;
        
        //List<PricebookEntry> pbe = [select id, name, CurrencyIsoCode from PriceBookEntry where Pricebook2id =: 'VALUE' and Product2.Id in: VALUE.keySet() ]; 
         /*PricebookEntry standardPBE1 = new PricebookEntry(Pricebook2Id = pricebookId, 
                                                        Product2Id = prod1.Id,   
                                                        UnitPrice = 10000, IsActive = true);
        insert standardPBE1;
        */        
        opportunityObj = (Opportunity)TestDataHelper.createSObject('Opportunity');        
        opportunityObj.Accountid= accountObj.id;   
        opportunityObj.Pricebook2Id=pricebookId;        
        opportunityObj.CurrencyIsoCode=standardPBE.CurrencyIsoCode;  
        opportunityObj.Organization__c=organizationObj.id;
        insert opportunityObj;
        
         opportunityObj = (Opportunity)TestDataHelper.createSObject('Opportunity');        
        opportunityObj.Accountid= accountObj.id;   
        opportunityObj.Pricebook2Id=pricebookId;        
        //opportunityObj.CurrencyIsoCode=standardPBE1.CurrencyIsoCode;   
        opportunityObj.Organization__c=organizationObj.id;
        insert opportunityObj;
        
        OpportunityTeamMember otm=new OpportunityTeamMember();
        otm.userid=userinfo.getuserid();
        otm.TeamMemberRole='High Level';
        otm.opportunityid=opportunityObj.id;
        otm.Lead_Type__c='Test Lead';
        
        insert otm;
         
        
        oliList = new List<OpportunityLineItem>();
        for(integer i = 0; i<= 5; i++) {
            opptyLineItemObj = new OpportunityLineItem();        
            opptyLineItemObj.Quantity=1;
            opptyLineItemObj.Oppty_Team_Members__c ='['+ otm.User.Name +','+ otm.Lead_Type__c +']';
            opptyLineItemObj.TotalPrice=500;
            opptyLineItemObj.Delivery_Date_Start__c = system.today().addDays(5);
            opptyLineItemObj.Delivery_Date_Last__c = system.today().addDays(7);
            opptyLineItemObj.Revenue_Date_Last__c = system.today().addDays(5);
            opptyLineItemObj.Revenue_Date_Start__c = system.today().addDays(7);
            opptyLineItemObj.Quote_Package_Name__c = 'packageName';
            //opptyLineItemObj.HasSchedule = true;
            opptyLineItemObj.PricebookEntryId=standardPBE.id; 
           // opptyLineItemObj.PricebookEntryId=standardPBE1.id; 
            opptyLineItemObj.opportunityid=opportunityObj.id;
            opptyLineItemObj.ServiceDate = system.today().addDays(5);
            opptyLineItemObj.Invoice_Date__c = system.today().addDays(5);
            
            oliList.add(opptyLineItemObj);
        }
        insert oliList;
    }
    
    
    
     static testmethod void testInsertOLI() {
        
        setData();
        /*
        List<OpportunityLineItem> olis = new List<OpportunityLineItem>();
        List<PricebookEntry> pbe = new List<PricebookEntry>();
        Opportunity oppty = TestDataHelper.createOpptyWithOfferings('Product',olis);
 */ 
        
        string oliIds = '';
       
        for (OpportunityLineItem oli : oliList) {
            oliIds = oliIds + ',' + oli.id;
        }
        oliIds = oliIds.substring(1);
        
        Test.startTest();
        ApexPages.currentPage().getParameters().put('opptyid',opportunityObj.id);
        ApexPages.currentPage().getParameters().put('ids',oliIds);
        
        OpportunityLineItemMultiInsert ctr = new OpportunityLineItemMultiInsert();
        ctr.save();
        ctr.cancel();
        //ctr.qtyToQtyHelper();
        ctr.olis = oliList;
        Boolean testValue;
        if(ctr != null){
        testValue = true;
        }
        System.assert(testValue); 
    }

}

 
Haneef SHaneef S
Hi steven,

I have tried your suggestion,
and still getting same error:
System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, Price Book Entry ID: id value of incorrect type: 00k9E000005VkOgQAK: [PricebookEntryId]

I have modified few changes and now the error is:
System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, OpportunityLineItemTrigger: execution of AfterInsert

caused by: System.NullPointerException: Attempt to de-reference a null object

Class.OpportunityLineItemHelper.createSchedules: line 1150, column 1
Trigger.OpportunityLineItemTrigger: line 113, column 1: []
The modified code is:
/*********************************
* Name: OpportunityLineItemMultiInsertTest
**********************************
* Purpose:  TA34060 Test class
* Created Date: 2018-10-12
**********************************/
@isTest

private class OpportunityLineItemMultiInsertTest {
    private static OpportunityLineItem opptyLineItemObj;
    private static Opportunity opportunityObj;
    private static List<OpportunityLineItem> oliList ;
    //Test.setCurrentPageReference(pageReference);
    
     private static void setData() {
        Account accountObj = (Account)TestDataHelper.createSObject('Account');
        accountObj.SAP_id__c='0011254999';
        accountObj.BillingCity = 'pune' ;        
        accountObj.BillingStreet = 'bhel chowk' ;        
        accountObj.BillingCountry = 'india' ;        
        accountObj.BillingPostalCode = '345210' ;
        insert accountObj;
        
        Organization__c organizationObj = (Organization__c)TestDataHelper.createSObject('Organization__c');        
        //organizationObj.Active__c = true;
        insert organizationObj; 
        
         RecordType rec = [Select id,name from recordtype where developername = 'Solution'];
        Product2 prod = new Product2(Name = 'Laptop X200', 
                                     Family = '2_PLA_BUSS', 
                                     Hierarchy_Level__c = 'SKU',
                                     ProductCode = 'abc123', 
                                     CanUseRevenueSchedule=true, 
                                     CanUseQuantitySchedule=true
                                    // recordtypeId = rec.id
                                    );
        insert prod;
      
       /* RecordType rec = [Select id,name from recordtype where developername = 'Solution'];
        Product2 prod1 = new Product2(Name = 'Laptop X200', 
                                     Family = '2_PLA_BUSS', 
                                     Hierarchy_Level__c = 'SKU',
                                     ProductCode = 'abc123', 
                                     CanUseRevenueSchedule=true, 
                                     CanUseQuantitySchedule=true,
                                      recordtypeId = rec.id
                                    );
        insert prod1;
        */
        Id pricebookId = Test.getStandardPricebookId();
        PricebookEntry standardPBE = new PricebookEntry(Pricebook2Id = pricebookId, 
                                                        Product2Id = prod.Id,   
                                                        UnitPrice = 10000, IsActive = true);
         system.debug(standardPBE);
        insert standardPBE;
        
        //List<PricebookEntry> pbe = [select id, name, CurrencyIsoCode from PriceBookEntry where Pricebook2id =: 'VALUE' and Product2.Id in: VALUE.keySet() ]; 
         /*PricebookEntry standardPBE1 = new PricebookEntry(Pricebook2Id = pricebookId, 
                                                        Product2Id = prod1.Id,   
                                                        UnitPrice = 10000, IsActive = true);
        insert standardPBE1;
        */        
        opportunityObj = (Opportunity)TestDataHelper.createSObject('Opportunity');        
        opportunityObj.Accountid= accountObj.id;   
        opportunityObj.Pricebook2Id=pricebookId;        
        opportunityObj.CurrencyIsoCode=standardPBE.CurrencyIsoCode;  
        opportunityObj.Organization__c=organizationObj.id;
        insert opportunityObj;
        
         opportunityObj = (Opportunity)TestDataHelper.createSObject('Opportunity');        
        opportunityObj.Accountid= accountObj.id;   
        opportunityObj.Pricebook2Id=pricebookId;        
        //opportunityObj.CurrencyIsoCode=standardPBE1.CurrencyIsoCode;   
        opportunityObj.Organization__c=organizationObj.id;
        insert opportunityObj;
        
        OpportunityTeamMember otm=new OpportunityTeamMember();
        otm.userid=userinfo.getuserid();
        otm.TeamMemberRole='High Level';
        otm.opportunityid=opportunityObj.id;
        otm.Lead_Type__c='Test Lead';
        
        insert otm;
         
        
        oliList = new List<OpportunityLineItem>();
        for(integer i = 0; i< 5; i++) {
            opptyLineItemObj = new OpportunityLineItem();        
            opptyLineItemObj.Quantity=1;
            opptyLineItemObj.Oppty_Team_Members__c ='['+ otm.User.Name +','+ otm.Lead_Type__c +']';
            opptyLineItemObj.TotalPrice=500;
            opptyLineItemObj.Delivery_Date_Start__c = system.today().addDays(5);
            opptyLineItemObj.Delivery_Date_Last__c = system.today().addDays(7);
            opptyLineItemObj.Revenue_Date_Last__c = system.today().addDays(5);
            opptyLineItemObj.Revenue_Date_Start__c = system.today().addDays(7);
            opptyLineItemObj.Quote_Package_Name__c = 'packageName';
            opptyLineItemObj.ServiceDate = system.today();
            opptyLineItemObj.Invoice_Date__c = system.today().adddays(5);
            //opptyLineItemObj.TotalQtyHelper__c = opptyLineItemObj.Quantity;
            //opptyLineItemObj.HasSchedule = true;
            opptyLineItemObj.PricebookEntryId=standardPBE.id; 
           // opptyLineItemObj.PricebookEntryId=standardPBE1.id; 
            opptyLineItemObj.opportunityid=opportunityObj.id;
            
            
            oliList.add(opptyLineItemObj);
        }
        insert oliList;
        system.debug('----'+oliList);
    }
    
    
    
     static testmethod void testInsertOLI() {
        
        setData();
        
        /*
        List<OpportunityLineItem> olis = new List<OpportunityLineItem>();
        List<PricebookEntry> pbe = new List<PricebookEntry>();
        Opportunity oppty = TestDataHelper.createOpptyWithOfferings('Product',olis);
 */ 
        
        string oliIds = '';
       
        for (OpportunityLineItem oli : oliList) {
          //  oliIds = oliIds + ',' + oli.PricebookEntryId;
            if (oliIds.length()>0) {
                        oliIds=oliIds+',';
                    }
            oliIds=oliIds+oli.PricebookEntryId;
            system.debug('oliIds===='+oliIds);
        }
        //oliIds = oliIds.substring(1);
        
        Test.startTest();
        ApexPages.currentPage().getParameters().put('opptyid',opportunityObj.id);
        ApexPages.currentPage().getParameters().put('ids',oliIds);
        
        OpportunityLineItemMultiInsert ctr = new OpportunityLineItemMultiInsert();
        ctr.save();
        ctr.cancel();
        //ctr.qtyToQtyHelper();
        ctr.olis = oliList;
        Boolean testValue;
        if(ctr != null){
        testValue = true;
        }
        System.assert(testValue); 
    }

}

If I comment ctr.save(); in test class the code coverage is 72%
I need help in extending the code coverage ,
Thanks,
Haneef