+ Start a Discussion
Linga_RaminLinga_Ramin 

code coverage help for below class

trigger PopulateStandardPrice2 on Product2 (before insert,before update,after insert,after update) {
    list<Id> Idlist = new list<Id>();
    list<product2> ProdsToUpdate = new list<Product2>();
    for(Product2 pr:trigger.new){
        Idlist.add(pr.Id);
    }
    pricebook2 pb = [select Id from pricebook2 where IsStandard = TRUE][0];
    Id stPrId = pb.Id;
    for(product2 p:[select Product_Price_Unit__c,Id from product2 where Id IN :Idlist]){
        for(pricebookentry pbe:[select Product2Id,UnitPrice from pricebookentry where pricebook2Id = :stPrId and product2Id IN :Idlist]){
            If((pbe.Product2Id == p.Id)&&(p.Product_Price_Unit__c!=pbe.UnitPrice)){
                p.Product_Price_Unit__c = pbe.UnitPrice;
                system.debug('this is it '+pbe.UnitPrice);
                system.debug('this is that '+p.Product_Price_Unit__c);
                ProdsToUpdate.add(p);
            }
        }
    }
    system.debug('ProdsToUpdate>>>'+ProdsToUpdate.size());
    If(ProdsToUpdate.size()>0&&trigger.isafter){
            update ProdsToUpdate;
    }
}
Deepali KulshresthaDeepali Kulshrestha
Hi,

you have to insert/create the record to cover this class.
Like this:-
use the code acccording to yourself
Product2 pro = new Product2(Name = 'iPhone X', Family = 'Mobile');
            Insert pro;
             
            //Instantiate the Pricebook2 record with StandardPricebookId
            Pricebook2 standardPricebook = new Pricebook2(
                Id = Test.getStandardPricebookId(),
                IsActive = true
            );
             
            //Execute an update DML on the Pricebook2 record, to make IsStandard to true
            Update standardPricebook;
             
            //Query for the Pricebook2 record, to check IsStandard field
            standardPricebook = [SELECT Id, IsStandard FROM Pricebook2 WHERE Id = :standardPricebook.Id];
            //It should return true
            System.assertEquals(true, standardPricebook.IsStandard);
             
             
            //Create the PricebookEntry
            PricebookEntry pbe = new PricebookEntry(
                Pricebook2Id = standardPricebook.Id,
                Product2Id = pro.Id,
                UnitPrice = 1020,
                IsActive = true
            );
            Insert pbe;
             
            //Query the PricebookEntry record
            pbe = [SELECT Id, Pricebook2.IsStandard FROM PricebookEntry];

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha