Here is the error message & my test class:

System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, This price definition already exists in this price book: []

public class Opportunity_LastStage_Test {

static testMethod void myTest() {

    //Create opp
    opportunity newopp = new opportunity();
        newopp.Name = 'Test Class 123 cek cek';
        newopp.Branch__c = 'Tanjung Priok';
        newopp.CloseDate = Date.Today();
        newopp.StageName = 'Generation';
        newopp.Interval__c = 12;
        newopp.Amount = 12000;
        newopp.Start_Date__c = date.today();
        insert newopp;

    Id pricebookId = Test.getStandardPricebookId();

    //Create product
    Product2 prod = new Product2();
         prod.Name = 'Product 123123123';
         prod.Service_Type__c = 'Kapal';
         prod.Price__c = 10000.00;
         prod.isActive = true;
         insert prod;

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

    //create opportunity line item. 
    OpportunityLineItem oli = new OpportunityLineItem();
         oli.OpportunityId = newopp.Id;
         oli.Quantity = 5;
         oli.PricebookEntryId = pbEntry.Id;
         oli.TotalPrice = oli.quantity * pbEntry.UnitPrice;
         insert oli;

    //create top
    Opportunity_Term_of_Payment__c newtop = new Opportunity_Term_of_Payment__c();
        newtop.Opportunity__c = newopp.Id;
        newtop.Document_Date__c = date.today();
        newtop.Amount__c = 999999;
        newtop.Description__c = 'test';
        insert newtop;

        newopp.StageName = 'Product Information';
        update newopp;


1 Answer 1


First, use @isTest(seeAllData=false)

Secondly, when you update Opportunity record, you need to separately execute SOQL query.

Opportunity Opp = [SELECT StageName FROM Opportunity WHERE Id =:newopp.Id];
Opp.StageName = 'Product Information';
update Opp;

Thirdly, If you are preparing the data use @testSetup so that data can be used in other methods in the same test class

Mention, System.assert() to verify text outcome.

Refer Testing Best Practices

  • Thanks ! .. I just realized that one of my team member created a workflow that automatically add pricebook Id .. I have to wait for him to change the workflow Jul 11, 2018 at 8:03

You must log in to answer this question.

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