You need to sign in to do that
Don't have an account?
HTANIRS
trigger test class coverage for opportunity lineitem
Hello Friends,
Need help in trigger test class code coverage. I am getting 53% code coverage.
Requirement: Checking Opportunity Line Item already exists in Opportunity. If exists display error.
Kindly check the code below and let me know what change need to be done.
Thanks.
Need help in trigger test class code coverage. I am getting 53% code coverage.
Requirement: Checking Opportunity Line Item already exists in Opportunity. If exists display error.
Kindly check the code below and let me know what change need to be done.
Trigger: trigger avoiddupOli on OpportunityLineItem (before insert) { System.debug('---Inside Oli Trigger---'); Map<Id,List<Id>> mapProduct = new Map<Id,List<Id>>(); Set<Id> setOppIds = new Set<Id>(); for(OpportunityLineItem oli: Trigger.new){ setOppIds.add(oli.OpportunityId); System.debug('--- Opportunity Id ---' + oli.OpportunityId); } for(OpportunityLineItem oli: [Select Id, Product2Id, OpportunityId from OpportunityLineItem where OpportunityId IN:setOppIds]){ if(mapProduct.containsKey(oli.OpportunityId)) mapProduct.get(oli.OpportunityId).add(oli.Product2Id); else mapProduct.put(oli.OpportunityId,new List<Id>{oli.Product2Id}); } for(OpportunityLineItem oli: Trigger.new){ if(mapProduct.containsKey(oli.OpportunityId)){ for(Id prodId: mapProduct.get(oli.OpportunityId)){ if(oli.Product2Id.equals(prodId)) oli.addError('Product already Exists'); System.debug('--- Product Error ---' + oli.Product2Id); } } } }
Test Class: @isTest(SeeAllData=true) public class avoiddupOliTest { static testMethod void testUnit() { Pricebook2 standardPb = [select id, name, isActive from Pricebook2 where IsStandard = true limit 1]; Id RecordTypeIdAccount = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Person Account').getRecordTypeId(); Account acc = new Account(LastName = 'Account Test', recordtypeid = RecordTypeIdAccount); insert acc; Opportunity opps = new Opportunity(Name = 'Test Opps', CloseDate = system.today(), StageName = 'New', AccountId = acc.Id); insert opps; product2 prod = new Product2(Name = 'Test Prod', entity_id__c = '98765'); insert prod; Pricebookentry pbey = new Pricebookentry(isActive = true, product2Id = prod.Id, UnitPrice = 50, Pricebook2ID = standardPb.id); insert pbey; Test.startTest(); OpportunityLineItem item = new OpportunityLineItem( pricebookentryid = pbey.Id, Name__c = 'Test Prod', product_id__c = '98765', TotalPrice = 100, Quantity = 1, OpportunityID = opps.Id ); try { insert item; } catch (Exception duplicate) { } Test.stopTest(); } }
Thanks.
All Answers
This is working fine now. Code Coverage is 85% and deployed into production.
Thanks for your help.