function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sreekanth reddysreekanth reddy 

Test Class for Trigger.

Hi,

This is my trigger and how to write test class for this trigger.

trigger OppProductDelete on OpportunityLineItem (before delete){
Id sysAdminId = [Select Id, Name from Profile where id = '00e90000001qXNbAAM' LIMIT 1].Id;
for (OpportunityLineItem oppProd : trigger.old){
if(UserInfo.getProfileId() ==sysAdminId)
oppProd.addError('This Opp Product may not be deleted');}
}

thanks.
Best Answer chosen by sreekanth reddy
Arunkumar RArunkumar R
Hi Srikanth,

1. Please do not hard code profile id to anywhere. User profile name instead of that.
2. To cover your trigger, you need to insert, opportunity, product, pricebook. Then finally delete it and assert the exception.

Find the modfied class and new test class, it will solve your problem.

Trigger
trigger OppProductDelete on OpportunityLineItem (before delete)
{
Id sysAdminId = [Select Id, Name from Profile where Name = 'System Administrator' LIMIT 1].Id;
for (OpportunityLineItem oppProd : trigger.old)
{
if(UserInfo.getProfileId() ==sysAdminId)
oppProd.addError('This Opp Product may not be deleted');
}
}

Test Class
 
@isTest
private class TestLineItemDelete
{
    
    static testMethod void deleteLineItem()
    {
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
        
        User u = new User(Alias = 'sys', Email='systemadmin@testorg.com', 
                          EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
                          LocaleSidKey='en_US', ProfileId = p.Id, 
                          TimeZoneSidKey='America/Los_Angeles', UserName='sysadmintest@ss.com');
        
        System.runAs(u)
        {
            // Insert Product
            Product2 pr = new Product2();
            pr.Name='Moto - G1';
            pr.isActive=true;
            insert pr;
            
            // Insert Pricebook
            PriceBook2 customPriceBook = new PriceBook2();
            customPriceBook.Name='Custom Pricebook';
            customPriceBook.IsActive=true;
            insert customPriceBook;
            
            // Query Standard and Custom Price Books
            Pricebook2 customPriceBookRec=[select Id from Pricebook2 where id=:customPriceBook.Id];
            Id stdPriceBookRec = Test.getStandardPricebookId();
            
            // Create Standard PriceBookEntry
            PriceBookEntry stdPriceBookEntry = new PriceBookEntry();
            stdPriceBookEntry.Product2Id=pr.Id;
            stdPriceBookEntry.Pricebook2Id=stdPriceBookRec;
            stdPriceBookEntry.UnitPrice=2000;
            stdPriceBookEntry.IsActive=true;
            insert stdPriceBookEntry;
            
            // Create Custom PriceBookEntry
            PriceBookEntry customPriceBookEntry = new PriceBookEntry();
            customPriceBookEntry.Product2Id=pr.Id;
            customPriceBookEntry.Pricebook2Id=customPriceBookRec.Id;
            customPriceBookEntry.UnitPrice=5000;
            customPriceBookEntry.IsActive=true;
            insert customPriceBookEntry;
            
            // Create Opportunity
            Opportunity opp = new Opportunity();
            opp.Name = 'Test';
            opp.CloseDate= System.Today();
            opp.StageName='Prospecting';
            insert opp;
            
            // Add product and Pricebook to the particular opportunity using OpportunityLineItem 
            OpportunityLineItem oppLineItem = new OpportunityLineItem();
            oppLineItem.OpportunityId = opp.Id;
            oppLineItem.PricebookEntryId = customPriceBookEntry.Id;
            oppLineItem.UnitPrice = 7000;
            oppLineItem.Quantity = 5;
            insert oppLineItem;
            
            try
            {
                delete oppLineItem;
            }
            catch(DmlException e)
            {
                system.assert(e.getMessage().contains('This Opp Product may not be deleted'));
            }
        }
    }
}

 

All Answers

Sagar PareekSagar Pareek
Hi Sreekant, 

Have you tried any snippet of code that you can share?

You need to first insert an opportunity  and then opportunity line item in your test class and then delete it. 

 
Arunkumar RArunkumar R
Hi Srikanth,

1. Please do not hard code profile id to anywhere. User profile name instead of that.
2. To cover your trigger, you need to insert, opportunity, product, pricebook. Then finally delete it and assert the exception.

Find the modfied class and new test class, it will solve your problem.

Trigger
trigger OppProductDelete on OpportunityLineItem (before delete)
{
Id sysAdminId = [Select Id, Name from Profile where Name = 'System Administrator' LIMIT 1].Id;
for (OpportunityLineItem oppProd : trigger.old)
{
if(UserInfo.getProfileId() ==sysAdminId)
oppProd.addError('This Opp Product may not be deleted');
}
}

Test Class
 
@isTest
private class TestLineItemDelete
{
    
    static testMethod void deleteLineItem()
    {
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
        
        User u = new User(Alias = 'sys', Email='systemadmin@testorg.com', 
                          EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
                          LocaleSidKey='en_US', ProfileId = p.Id, 
                          TimeZoneSidKey='America/Los_Angeles', UserName='sysadmintest@ss.com');
        
        System.runAs(u)
        {
            // Insert Product
            Product2 pr = new Product2();
            pr.Name='Moto - G1';
            pr.isActive=true;
            insert pr;
            
            // Insert Pricebook
            PriceBook2 customPriceBook = new PriceBook2();
            customPriceBook.Name='Custom Pricebook';
            customPriceBook.IsActive=true;
            insert customPriceBook;
            
            // Query Standard and Custom Price Books
            Pricebook2 customPriceBookRec=[select Id from Pricebook2 where id=:customPriceBook.Id];
            Id stdPriceBookRec = Test.getStandardPricebookId();
            
            // Create Standard PriceBookEntry
            PriceBookEntry stdPriceBookEntry = new PriceBookEntry();
            stdPriceBookEntry.Product2Id=pr.Id;
            stdPriceBookEntry.Pricebook2Id=stdPriceBookRec;
            stdPriceBookEntry.UnitPrice=2000;
            stdPriceBookEntry.IsActive=true;
            insert stdPriceBookEntry;
            
            // Create Custom PriceBookEntry
            PriceBookEntry customPriceBookEntry = new PriceBookEntry();
            customPriceBookEntry.Product2Id=pr.Id;
            customPriceBookEntry.Pricebook2Id=customPriceBookRec.Id;
            customPriceBookEntry.UnitPrice=5000;
            customPriceBookEntry.IsActive=true;
            insert customPriceBookEntry;
            
            // Create Opportunity
            Opportunity opp = new Opportunity();
            opp.Name = 'Test';
            opp.CloseDate= System.Today();
            opp.StageName='Prospecting';
            insert opp;
            
            // Add product and Pricebook to the particular opportunity using OpportunityLineItem 
            OpportunityLineItem oppLineItem = new OpportunityLineItem();
            oppLineItem.OpportunityId = opp.Id;
            oppLineItem.PricebookEntryId = customPriceBookEntry.Id;
            oppLineItem.UnitPrice = 7000;
            oppLineItem.Quantity = 5;
            insert oppLineItem;
            
            try
            {
                delete oppLineItem;
            }
            catch(DmlException e)
            {
                system.assert(e.getMessage().contains('This Opp Product may not be deleted'));
            }
        }
    }
}

 
This was selected as the best answer
ManojjenaManojjena
Hi Sreekanth,

Please use below code it will help you to solve your problem .
But only thing is that in each record level you have to give the mandatory fields as per your organisation .
 
@isTest(SeeAllData=true)
  private class TestOppProductDeleteOne {
   public static testMethod void unitTest() {
      Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; 
      User u = new User(Alias = 'standt', Email='standarduser@testorg.com', 
      EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
      LocaleSidKey='en_US', ProfileId = p.Id, 
      TimeZoneSidKey='America/Los_Angeles', UserName=Datetime.now().getTime() + 'test@xxx.com');

      System.runAs(u) {
        Account acc=new Account();
          acc.Name='TestAcc';
          insert acc;
         
      Product2 newProd = new Product2();
          newProd.Name = 'test product';
          newProd.family = 'test family';
          insert newProd;

     PriceBookEntry pbEntry = new PriceBookEntry();
        pbEntry.UnitPrice = 300;
        pbEntry.PriceBook2Id = [select id from PriceBook2 where isStandard = true].Id;
        pbEntry.Product2Id = newProd.Id;
        pbEntry.IsActive = true;
       insert pbEntry ;
     Opportunity opp=new Opportunity();
          opp.AccountId=acc.id;
          opp.Name='TestOpp';
          opp.closeDate=System.Today().addMonths(5);
          Opp.StageName='Prospecting';
          opp.Pricebook2Id=pbEntry.PriceBook2Id;
          insert opp;
    
    OpportunityLineItem oppLitem=new opportunitylineItem();
          oppLitem.pricebookentryid=pbEntry.Id; 
         oppLitem.Quantity=1; 
         oppLitem.OpportunityId=opp.id; 
         oppLitem.TotalPrice=1000;
         Insert oppLitem;
         delete oppLitem;
      }
   }
}

 
sreekanth reddysreekanth reddy
Thanks arun it's working fine.
sreekanth reddysreekanth reddy
Thanks manoj for your responce.