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
Ryan Dempsey 12Ryan Dempsey 12 

Getting Field_Custom_Validation Error when testing Trigger that prevents deletion of opp lines

I am an admin without delevoping skills and am getting the following error "System.DmlException: Delete failed. First exception on row 0 with id 00k1g0000081vIZAAY; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Only a system administrator can delete line items: []" when running the test or when trying to validate a change set with the following trigger and test class.  I poached most of this from the community. I'm wondering if the error has something to do with the profile permissions for the running user? Those with the enrollment profile do not have permissions to create pricebooks. When I replace "Enrollment" with "System Administrator" in the system user profile assignment of the test class, I no longer get those errors and I get my code coverage etc but that's not the test I want to run. I want System admins to be able to delete Opp lines and want to prevent everyone else from deleting them. I'm not even sure if that is what was generating the initial error, but IF it is, would anyone have any ideas on how to handle this in my test. Would I need to insert a system admin user as well and create the pricebook as that system admin and allow the rest of the test to be executed as user with the enrollment profile? 


This is the Trigger. 
trigger preventOppLineDelete on OpportunityLineItem (before delete) 
{
    String profileName=[SELECT id,Name FROM Profile WHERE Id =:UserInfo.getProfileId()].Name ;  
    for (OpportunityLineItem a : Trigger.old)
    {      
        If(profileName!='System Administrator')
        {
            a.addError('Only a system administrator can delete line items');
        }
    }
    
}

This is the Test Class
@isTest
private class PreventOpportunityProdTest {
    public static testMethod void testRunAs() {
        // Setup test data
        // This code runs as the system user
        Profile p = [SELECT Id FROM Profile WHERE Name='Enrollment']; 
        User u = new User(Alias = 'standt', Email='stanstandardusesdasdasdrdarduser@testorg.com', 
            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', ProfileId = p.Id, 
            TimeZoneSidKey='America/Los_Angeles', UserName='enrollment@testorg.com');

        System.runAs(u) {
           Account a = new Account();
        a.Name = 'Test';
        a.RecordTypeId ='0125A000001IgHoQAK';
     
        
        insert a;
        
        
        Opportunity o = new Opportunity();
        o.name = 'Test';
        o.AccountId = a.Id;
        o.StageName = 'Initial App Received';
        o.CloseDate = date.today();
      
        
        insert o;
    
     Pricebook2 pb22 = new Pricebook2(Name='Test Price Book');
 insert pb22;

Product2 pro2 = new Product2(Name='BXCD',  isActive=true);
insert pro2;
            
PricebookEntry pbe2 =new PricebookEntry(unitprice=0.01,Product2Id=pro2.Id,Pricebook2Id=Test.getStandardPricebookId(),
                                        isActive=true,UseStandardPrice = false);
             insert pbe2;
            

 OpportunityLineItem OPplineitem2 = new OpportunityLineItem (Quantity=2, OpportunityId=o.Id,UnitPrice=0.02,PriceBookEntryId=pbe2.Id );
 insert OPplineitem2;
 
    
    delete OPplineitem2 ;
        }
    }
}
VinayVinay (Salesforce Developers) 
Hi Ryan,

This is working as expected,  Try to insert/update/delete test data which doesn't matchest that validation "Only a system administrator can delete line items" criteria.

Thanks,
Ryan Dempsey 12Ryan Dempsey 12
Well when I test this in the UI, Yes it works fine. I tested as system admin and it allows me to delete and when I try to delete as someone else, I get the error.  But I'm worried about there being an error generated in my test run and when I try to validate the change set when I try to deploy. So You're saying I can go ahead and deploy the change set even though it's having that error because that error is the Error we WANT our test to generate?