My test class works fine in sandbox. But When I'm validating this in production getting error mentioned below:

OpportunityLineItem opli2 = new OpportunityLineItem();
        opli2.UnitPrice = 57;
        opli2.Quantity =1;
        insert opli2; // Stacktrace Line where insert failed and throwing exception

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]

Any helping hand will really be appreciated.

1 Answer 1


First of all, the error is quite clear:


has no child PriceBookEntry record corresponding to customPrice.Id

No, as to why it fails in PROD deployment rather than sandbox, I can think of two likely possibilities:

  1. Your test method is not mocking Pricebooks, Products, and PricebookEntries but instead relying on org data and these are different between sandbox and PROD
  2. Your test method draws on some custom setting, custom label, or custom metadata that defines the value used for customPrice.Id and that configuration data is not set up correctly in PROD.

In general, best practice is for testmethods to mock all data they need and to not rely on any org data. This ensures that the testmethod runs successfully over and over again, regardless of changes to configuration and setup data.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .