[SalesForce] Price book entry is in a different pricebook than the one assigned to the opportunity

I am facing the issue while deploying the test class in production. The test class is working fine in sandbox but failing in production

System.DmlException: Insert failed. First exception on row 0; first
error: FIELD_INTEGRITY_EXCEPTION, field integrity exception:
PricebookEntryId (pricebook entry is in a different pricebook than the
one assigned to the opportunity): [PricebookEntryId]

Here is my code

 @isTest
public class CopytoOppLineItemTest{

     @isTest static void testTrigger(){

         Id pricebookId = Test.getStandardPricebookId();
         //Pricebook2  pb = [select name,id from Pricebook2 where  IsStandard =true  LIMIT 1];

        system.debug('pricebookId !!'+pricebookId );

         Product2 prod = new Product2(
             Name = 'Product X',
             ProductCode = 'Pro-X',
             isActive = true
        );
        insert prod;

        //Create your pricebook entry
        PricebookEntry pbEntry = new PricebookEntry(
             Pricebook2Id =  pricebookId ,
             Product2Id = prod.Id,
             UnitPrice = 100.00,
             IsActive = true
        );
        insert pbEntry;



        Opportunity op = new Opportunity();
        op.name = 'test';
        op.closedate = Date.today();
        op.StageName = 'Init';
        op.pricebook2Id  = pricebookId   ;
        insert op;
        system.debug('op.pricebook2Id!!!!'+op.pricebook2Id+'pbEntry.Pricebook2Id !!!'+pbEntry.Pricebook2Id);

         OpportunityLineItem  ol = new OpportunityLineItem();
         ol.opportunityid = op.id;
         ol.quantity = 4;       
         ol.TotalPrice = ol.quantity * pbEntry.UnitPrice ;
         ol.PricebookEntryId = pbEntry.id ;

         insert ol;

     }



}

I have also checked the values in debug in production, the value of opportunity pricebookid and pricebookentry pricebookid are the same

(system.debug('op.pricebook2Id!!!!'+op.pricebook2Id+'pbEntry.Pricebook2Id
!!!'+pbEntry.Pricebook2Id);)

Please help me on this issue.

Best Answer

You most likely have a Process Builder or a trigger, or wfr setting the price book on insert of the opportunity.

You did debug and that is good but you only debugged what you created not the results after it was committed to the database.

Before your debug, query for the opportunity and check if the pricebook2id is the same and what your set it to be:

Opportunity tmp = [Select PriceBook2Id from Opportunity Where Id = :op.id];
system.assertEquals(pricebookId,tmp.PriceBook2Id,'The Opportunity price book was modified after it was inserted');
Related Topic