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
Lili ChavesLili Chaves 

Help with a unit test on a simple trigger

Help with a unit test on a simple trigger
I have created a simple "before delete" trigger for Leads based on the current user's profile name, and it is working like a charm in Sandbox.  I have tried to write a unit test but have not had any luck. I downloaded a Test Generator app to assist and this is what I have so far. Can anyone please help! 

This is my trigger:

 trigger LeadDeleletionLQS on Lead (before delete) {

 //Prevent the deletion of leads of the current user is assigned the 
Lead Qualification Specialist profile.
  Id userProfileId = userinfo.getProfileId();
  String userProfileName = [SELECT ID, Name from Profile Where Id = : userProfileId].Name;
  
  for(Lead lead : trigger.old){ 
  if(userProfileName == 'Lead Qualification Specialist'){   

       lead.adderror('You do not have the permission to merge Leads, contact SalesOp');

        }

    }

}


Here is my draft of a unit test: 

@isTest
    private class LeadDeleletionLQS_Test {
 @isTest static void test_LeadDeleletionLQSU (){
    // Test data setup 
    // Create a Lead, then try to delete it
    Lead lead_obj = new Lead(LastName = 'LastName286', FirstName = 'First968', Company = 'Company326', Street = 'PratapNagar', City = 'Jaipur', State = 'TX', Phone = '54343-37369', LeadSource = 'TBD', Status = 'New');
    Insert lead_obj; 
    Id userProfileId = userinfo.getProfileId();
    String userProfileName = [SELECT ID, Name from Profile Where Id = : userProfileId].Name;
    if(userProfileName == 'Lead Qualification Specialist') 
    

    //Perform test
    Test.startTest();
    Database.DeleteResult result = Database.delete (lead_obj,false);
    Test.stopTest();
    // Verify 
    //In this case the deletion should have been stopped by the trigger,
    // so verify that we got back an error. 
    System.assert(!result.isSuccess());
    System.assert(result.getErrors().size() > 0);
    System.assertEquals('You do not have the permission to merge Leads, contact SalesOp',
                         result.getErrors()[0].getMessage());
    }
    
}
Best Answer chosen by Lili Chaves
Naren9Naren9
Hi Lili,
Use the below code. I have tested in my org and Test coverage is 100%
First Create a Profile - Lead Qualification Specialist.I hope you have this profile in your org.

@isTest
public class LeadDeleletionLQSTest {
    @isTest Static Void TestLeadDeletion()
    {
        // Setup test data
        // Create a unique UserName
        String uniqueUserName = 'standarduser' + DateTime.now().getTime() + '@testorg.com';
        // This code runs as the system user
        Profile p = [SELECT Id FROM Profile WHERE Name='Lead Qualification Specialist'];
        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=uniqueUserName);
        System.runAs(u) {
              // The following code runs as user 'u'
              System.debug('Current User: ' + UserInfo.getUserName());
              System.debug('Current Profile: ' + UserInfo.getProfileId());
            Lead lead_obj = new Lead(LastName = 'LastName286', FirstName = 'First968', Company = 'Company326', Street = 'PratapNagar', City = 'Jaipur', State = 'TX', Phone = '54343-37369', LeadSource = 'TBD', Status = 'New');
            Insert lead_obj;
            
           
            //System.asserEquals(deletedAccount.IsDeleted, true);
            try {  
                     Lead d = [SELECT Id FROM Lead WHERE Id = :lead_obj.Id];
                    delete d;    
                    System.Assert(false, 'This was supposed to fail');  
                }
            catch(DMLException e)
            {  
            System.assert(true, 'Deletion failed appropriately');
            }
          }
    }

}

Thanks,
Narendar

All Answers

Karan KeharKaran Kehar
Hi Lili,

In the test class you are checking for profile equals  Lead Qualification Specialist.
When the test is executed, the userinfo class will store your user information which is not Lead Qualification Specialist as you are the admin. Due to this some part of the trigger is not getting covered.

What you could do is to create a user in test class with profile Lead Qualification Specialist and then use system.runas functionality in your test.You can find syste.runas documentation below.

This link will walk you through to create user in test class and use runas

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_tools_runas.htm

If this helps, please mark it as best answer
Naren9Naren9
Hi Lili,
Use the below code. I have tested in my org and Test coverage is 100%
First Create a Profile - Lead Qualification Specialist.I hope you have this profile in your org.

@isTest
public class LeadDeleletionLQSTest {
    @isTest Static Void TestLeadDeletion()
    {
        // Setup test data
        // Create a unique UserName
        String uniqueUserName = 'standarduser' + DateTime.now().getTime() + '@testorg.com';
        // This code runs as the system user
        Profile p = [SELECT Id FROM Profile WHERE Name='Lead Qualification Specialist'];
        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=uniqueUserName);
        System.runAs(u) {
              // The following code runs as user 'u'
              System.debug('Current User: ' + UserInfo.getUserName());
              System.debug('Current Profile: ' + UserInfo.getProfileId());
            Lead lead_obj = new Lead(LastName = 'LastName286', FirstName = 'First968', Company = 'Company326', Street = 'PratapNagar', City = 'Jaipur', State = 'TX', Phone = '54343-37369', LeadSource = 'TBD', Status = 'New');
            Insert lead_obj;
            
           
            //System.asserEquals(deletedAccount.IsDeleted, true);
            try {  
                     Lead d = [SELECT Id FROM Lead WHERE Id = :lead_obj.Id];
                    delete d;    
                    System.Assert(false, 'This was supposed to fail');  
                }
            catch(DMLException e)
            {  
            System.assert(true, 'Deletion failed appropriately');
            }
          }
    }

}

Thanks,
Narendar
This was selected as the best answer
Naren9Naren9
If this helps, please mark it as best answer.
 
Lili ChavesLili Chaves
Hey Narendar, 

I keep getting this error. 

The value of the "id" parameter contains a character that is not allowed or the value exceeds the maximum allowed length. Remove the character from the parameter value or reduce the value length and resubmit. If the error still persists, report it to our Customer Support team. Provide the URL of the page you were requesting as well as any other related information. 

Any idea why? 
 
Naren9Naren9
Hi Lili,
Are you getting this error in Test Class or Actual Trigger?
On Error, double click, you will get the line number and column.

Thanks,
Naren
Lili ChavesLili Chaves
Naren, thank you so much it worked perfectly you da men!