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
brozinickrbrozinickr 

Not able to get code coverage

I'm having an issue with my test coverage.  I recently built a trigger that doesn't allow anyone except for Sys Admins to insert or delete certain types of opportunities.  The triggers work fine, I just cant get the code coverage on my delete part.  Since I the reps can't insert the records, I'm thinking that's where it's failing, but in my test code I am testing it so a system administrator create the opportunity and then the standard user is deleting it.  Not sure why it's not working.

 

@IsTest
private class TestTrgCannotDeleteAcctMgmtRenewal
{
    static testMethod void testDelete()
    {
      Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
      User u = new User(Alias = 'sysadmin', Email='saplingsysadmin@testorg.com',
      EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
      LocaleSidKey='en_US', ProfileId = p.Id,
      TimeZoneSidKey='America/Los_Angeles', UserName='saplingsysadmin@testorg.com');

      test.starttest();
      System.runAs(u) {
      
      try
           {
           Account a=new Account(Name='Test Account');
           insert a;

           Opportunity o = new Opportunity(Name='Test Opportunity',
           closedate=system.today(), stagename='Discovery',Type='Acct. Mgmt. Renewal',LeadSource = 'Marketing Mailer');
           insert o;
           delete o;
           }
           catch (Exception e)
           {
           system.debug('Error:'+e);

} 
         
        }
  test.stopTest();
      }


    static testMethod void testDeleteFail()
    {
      Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
      User u1 = new User(Alias = 'standa', Email='saplingstandarduser@testorg.com',
      EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
      LocaleSidKey='en_US', ProfileId = p.Id,
      TimeZoneSidKey='America/Los_Angeles', UserName='saplingstandarduser@testorg.com');
      
      Profile p2 = [SELECT Id FROM Profile WHERE Name='System Administrator'];
      User u2 = new User(Alias = 'sysadmin', Email='saplingsysadmin@testorg.com',
      EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
      LocaleSidKey='en_US', ProfileId = p2.Id,
      TimeZoneSidKey='America/Los_Angeles', UserName='saplingsysadmin@testorg.com');

      test.starttest();
      System.runAs(u2) {
      
      try
           {
           Account a=new Account(Name='Test Account');
           insert a;

           Opportunity o = new Opportunity(Name='Test Opportunity',
           closedate=system.today(), stagename='Discovery',Type='Acct. Mgmt. Renewal',LeadSource = 'Marketing Mailer');
           System.runAs(u1){
           delete o;}
              // should throw an exception - the following assertion will cause an error if the code carries on
           }
           catch (Exception e)
           {
           system.debug('Error:'+e);

} 
         
        }
  test.stopTest();
      }
     
      
      static testMethod void testInsert()
    {
      Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
      User u = new User(Alias = 'sysadmin', Email='saplingsysadmin@testorg.com',
      EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
      LocaleSidKey='en_US', ProfileId = p.Id,
      TimeZoneSidKey='America/Los_Angeles', UserName='saplingsysadmin@testorg.com');

      test.starttest();
      System.runAs(u) {
      
      try
           {
           Account a=new Account(Name='Test Account');
           insert a;

           Opportunity o = new Opportunity(Name='Test Opportunity',
           closedate=system.today(), stagename='Discovery',Type='Acct. Mgmt. Renewal',LeadSource = 'Marketing Mailer');
           insert o;
           }
           catch (Exception e)
           {
           system.debug('Error:'+e);

} 
         
        }
  test.stopTest();
      }

    static testMethod void testInsertFail()
    {
      Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
      User u1 = new User(Alias = 'standa', Email='saplingstandarduser@testorg.com',
      EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
      LocaleSidKey='en_US', ProfileId = p.Id,
      TimeZoneSidKey='America/Los_Angeles', UserName='saplingstandarduser@testorg.com');

      test.starttest();
      System.runAs(u1) {
      
      try
           {
           Account a=new Account(Name='Test Account');
           insert a;

           Opportunity o = new Opportunity(Name='Test Opportunity',
           closedate=system.today(), stagename='Discovery',Type='Acct. Mgmt. Renewal',LeadSource = 'Marketing Mailer');
           insert o;
              // should throw an exception - the following assertion will cause an error if the code carries on
           }
           catch (Exception e)
           {
           system.debug('Error:'+e);

} 
         
        }
  test.stopTest();
      }
      
}

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
SFAdmin5SFAdmin5

alright so i think i might have got this.  i slightly modified your trigger and then wrote my own test class.  i get 88% (i had 90% then really wanted 100% but can't remember what i changed and now I can't get back to it, oh well), which beats 66% and is enough to get to production.

 

try this trigger and test class and let me know

 

trigger:

trigger CannotDeleteAcctMgmtRenewal on Opportunity (before insert, before delete) 

{

    Profile p = [SELECT Id from Profile where Name='System Administrator'];

        if(System.Trigger.IsDelete)
        {       
            for (Opportunity opps : trigger.old)
                if (UserInfo.getProfileId() != p.Id && (Opps.Type == 'Acct. Mgmt. Renewal'||Opps.Type == 'Acct. Mgmt. Supersede'||Opps.Type == 'Acct. Mgmt. Late Renewal'||Opps.Type == 'Acct. Mgmt. TER'))
                {
                 opps.addError('Error: You cannot delete an Account with a Client ID. Please contact your Salesforce.com Administrator for assistance.');
                }
         
        }
        
        if(System.Trigger.IsInsert)
        {
            for (Opportunity Opps : trigger.new)
                if (UserInfo.getProfileId() != p.Id && (Opps.Type == 'Acct. Mgmt. Renewal'||Opps.Type == 'Acct. Mgmt. Supersede'||Opps.Type == 'Acct. Mgmt. Late Renewal'||Opps.Type == 'Acct. Mgmt. TER'))
                {
                Opps.addError('Error:  You do not have the permissions create Acct. Mgmt. Renewal opportunities.  Please contact a System Administrator or your designated Ad Operations Specialist.');
                }
        }
       
}

 

test class:

 

@IsTest
private class TestTrgCannotDeleteAcctMgmtRenewal
{
    private static testMethod void testDeleteSucceed()
    {
        Opportunity opp = new Opportunity();
        opp.Name = 'test';
        opp.CloseDate = System.today();
        opp.StageName = 'Prospecting';
        insert opp; 
        delete opp;
    }

    private static testMethod void testDeleteFail()
    {
        Opportunity opp =new Opportunity(Name='Test Opp',StageName = 'Prospecting',Type ='Acct. Mgmt. Renewal',CloseDate = System.today());
        insert opp;
           
        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
        User u = new User(Alias = 'sysadmin', Email='saplingsysadmin@testorg.com',
            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
            LocaleSidKey='en_US', ProfileId = p.Id,
            TimeZoneSidKey='America/Los_Angeles', UserName='saplingsysadmin@testorg.com');

        System.runAs(u) 
        {
            try
            {
            delete opp;
            }
            catch (DMLException e)
            {
            system.debug('Error:'+e);
            }
        }
    }
         
    private static testMethod void testInsertSucceed()
    {
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
        User u = new User(Alias = 'sysadmin', Email='saplingsysadmin@testorg.com',
        EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
        LocaleSidKey='en_US', ProfileId = p.Id,
        TimeZoneSidKey='America/Los_Angeles', UserName='saplingsysadmin@testorg.com');

        System.runAs(u) 
        {     
            try
            {
                Account a=new Account(Name='Test Account');
                insert a;

                Opportunity o = new Opportunity(Name='Test Opp',StageName = 'Prospecting',Type ='Acct. Mgmt. Renewal',CloseDate = System.today());
                insert o;
            }
            catch (Exception e)
            {
                system.debug('Error:'+e);
            }  
        }
    }

    private static testMethod void testInsertFail()
    {
        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
        User u1 = new User(Alias = 'standa', Email='saplingstandarduser@testorg.com',
        EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
        LocaleSidKey='en_US', ProfileId = p.Id,
        TimeZoneSidKey='America/Los_Angeles', UserName='saplingstandarduser@testorg.com');

        System.runAs(u1) 
        {     
            try
            {
                Account a=new Account(Name='Test Account');
                insert a;

                Opportunity o = new Opportunity(Name='Test Opportunity',CloseDate=system.today(), StageName='Discovery',Type='Acct. Mgmt. Renewal',LeadSource = 'Marketing Mailer');
                insert o;
            }
            catch (Exception e)
            {
                 system.debug('Error:'+e);
            }          
        }
    }      
}

 

All Answers

SFAdmin5SFAdmin5

can you please post the trigger?  thanks

brozinickrbrozinickr
trigger CannotDeleteAcctMgmtRenewal on Opportunity (before insert, before delete) {

Profile adminId = [SELECT Id from Profile where Name='System Administrator' LIMIT 1];

if(System.Trigger.IsDelete && UserInfo.getProfileId() != adminId.Id)
        {
        for (Opportunity Opps : trigger.old)
            if ((Opps.Type == 'Acct. Mgmt. Renewal')||(Opps.Type == 'Acct. Mgmt. Supersede')||(Opps.Type == 'Acct. Mgmt. Late Renewal')||(Opps.Type == 'Acct. Mgmt. TER'))
          
                {
                Opps.addError('Error:  You do not have the permissions to delete Acct. Mgmt. Renewal opportunities.  Please contact a System Administrator or your designated Ad Operations Specialist.');
                }
        }
        
if(System.Trigger.IsInsert && UserInfo.getProfileId() != adminId.Id)
        {
        for (Opportunity Opps : trigger.new)
            if ((Opps.Type == 'Acct. Mgmt. Renewal')||(Opps.Type == 'Acct. Mgmt. Supersede')||(Opps.Type == 'Acct. Mgmt. Late Renewal')||(Opps.Type == 'Acct. Mgmt. TER'))
          
                {
                Opps.addError('Error:  You do not have the permissions create Acct. Mgmt. Renewal opportunities.  Please contact a System Administrator or your designated Ad Operations Specialist.');
                }
        }
        
}

 

 

crop1645crop1645

I think the issue is that std users don't have CRUD permission to delete objects they didn't create or aren't higher in the role hierarchy -- https://help.salesforce.com/HTViewSolution?id=000005672&language=en_US 

 

The trigger may not even be executing.

 

I had similar issues and ended up with a somewhat elaborate scheme wherein I ensured my std user was higher in the role hierarchy than the user that created the sobject; then the test was system.runAs(stdUser) 

brozinickrbrozinickr

When I test it manually when I login as a user, it works perfectly fine, that's why I am confused on why it's failing.  I did check my crud permissions for the standard user and they do have the permissions to create, read, update, and delete.

 

SFAdmin5SFAdmin5

yeah i've actually been trying to get a test class to get this trigger to pass coverage but i've been stuck at 66%.  you're right this trigger does work, at least it does for initial ui/one-off testing (i haven't even tried bulk testing it yet).  i'm going to keep trying to get a test class for this but if anyone gets it past 75% at least pls post the code.  thanks.

brozinickrbrozinickr

Thanks for taking time to look at this Ross, I really appreciate it!  I'll keep on playing around with too to see if I can figure it out and let everyone know.

SFAdmin5SFAdmin5

alright so i think i might have got this.  i slightly modified your trigger and then wrote my own test class.  i get 88% (i had 90% then really wanted 100% but can't remember what i changed and now I can't get back to it, oh well), which beats 66% and is enough to get to production.

 

try this trigger and test class and let me know

 

trigger:

trigger CannotDeleteAcctMgmtRenewal on Opportunity (before insert, before delete) 

{

    Profile p = [SELECT Id from Profile where Name='System Administrator'];

        if(System.Trigger.IsDelete)
        {       
            for (Opportunity opps : trigger.old)
                if (UserInfo.getProfileId() != p.Id && (Opps.Type == 'Acct. Mgmt. Renewal'||Opps.Type == 'Acct. Mgmt. Supersede'||Opps.Type == 'Acct. Mgmt. Late Renewal'||Opps.Type == 'Acct. Mgmt. TER'))
                {
                 opps.addError('Error: You cannot delete an Account with a Client ID. Please contact your Salesforce.com Administrator for assistance.');
                }
         
        }
        
        if(System.Trigger.IsInsert)
        {
            for (Opportunity Opps : trigger.new)
                if (UserInfo.getProfileId() != p.Id && (Opps.Type == 'Acct. Mgmt. Renewal'||Opps.Type == 'Acct. Mgmt. Supersede'||Opps.Type == 'Acct. Mgmt. Late Renewal'||Opps.Type == 'Acct. Mgmt. TER'))
                {
                Opps.addError('Error:  You do not have the permissions create Acct. Mgmt. Renewal opportunities.  Please contact a System Administrator or your designated Ad Operations Specialist.');
                }
        }
       
}

 

test class:

 

@IsTest
private class TestTrgCannotDeleteAcctMgmtRenewal
{
    private static testMethod void testDeleteSucceed()
    {
        Opportunity opp = new Opportunity();
        opp.Name = 'test';
        opp.CloseDate = System.today();
        opp.StageName = 'Prospecting';
        insert opp; 
        delete opp;
    }

    private static testMethod void testDeleteFail()
    {
        Opportunity opp =new Opportunity(Name='Test Opp',StageName = 'Prospecting',Type ='Acct. Mgmt. Renewal',CloseDate = System.today());
        insert opp;
           
        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
        User u = new User(Alias = 'sysadmin', Email='saplingsysadmin@testorg.com',
            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
            LocaleSidKey='en_US', ProfileId = p.Id,
            TimeZoneSidKey='America/Los_Angeles', UserName='saplingsysadmin@testorg.com');

        System.runAs(u) 
        {
            try
            {
            delete opp;
            }
            catch (DMLException e)
            {
            system.debug('Error:'+e);
            }
        }
    }
         
    private static testMethod void testInsertSucceed()
    {
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
        User u = new User(Alias = 'sysadmin', Email='saplingsysadmin@testorg.com',
        EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
        LocaleSidKey='en_US', ProfileId = p.Id,
        TimeZoneSidKey='America/Los_Angeles', UserName='saplingsysadmin@testorg.com');

        System.runAs(u) 
        {     
            try
            {
                Account a=new Account(Name='Test Account');
                insert a;

                Opportunity o = new Opportunity(Name='Test Opp',StageName = 'Prospecting',Type ='Acct. Mgmt. Renewal',CloseDate = System.today());
                insert o;
            }
            catch (Exception e)
            {
                system.debug('Error:'+e);
            }  
        }
    }

    private static testMethod void testInsertFail()
    {
        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
        User u1 = new User(Alias = 'standa', Email='saplingstandarduser@testorg.com',
        EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
        LocaleSidKey='en_US', ProfileId = p.Id,
        TimeZoneSidKey='America/Los_Angeles', UserName='saplingstandarduser@testorg.com');

        System.runAs(u1) 
        {     
            try
            {
                Account a=new Account(Name='Test Account');
                insert a;

                Opportunity o = new Opportunity(Name='Test Opportunity',CloseDate=system.today(), StageName='Discovery',Type='Acct. Mgmt. Renewal',LeadSource = 'Marketing Mailer');
                insert o;
            }
            catch (Exception e)
            {
                 system.debug('Error:'+e);
            }          
        }
    }      
}

 

This was selected as the best answer
brozinickrbrozinickr

I just tested this and works great.  It's weird that it's saying that the error message isn't covered by the test code coverage when it highlights the if condition.  Oh well, it is what it is.  Thanks for your hard work and help with this, I really appreciate it! :)