[SalesForce] TestClass User Creation and system.runAs()

I have a requirement for a Trigger on Opportunity while creating a new Opportunity as,

  1. Add the Opportunity Owners Manager to Opportunity Team Member with role "Sales Manager"

  2. And if Opportunity Owner itself is a Manager, then add the below user as "Sales Rep" in Opportunity Team member.

I was able to write an After Trigger on Opportunity object and it works fine. I have written Test class to test this and working fine as expected. But I just need to know the way I use User Creation and system.runAs() are correct.

Specifically I need to verify my logic inside the

initTestUser(String userName) method

and

the Opportunity Owner assignment inside system.runAs()

while creating New user and Opportunity with respective users are
correct, as I am using this first time.

@IsTest
public class OppTriggerTest {
      @IsTest static void OppCrtStandAlnUsr1(){ //1. Opp created by a StandAlone user with No Manager or Enployee to Report to this user - --- No OpportunityTeam mbr
        Opportunity opp                     = new Opportunity();
        opp.Name                            = 'Testing1';
        opp.CloseDate                       = Date.today() + 30;
        opp.StageName                       = 'Prospecting';

        User userToCreate                   = initTestUser('robiadmincml1');
        insert userToCreate;

        system.runAs(userToCreate){ 
            //opp.OwnerId                   = userToCreate.Id; //No need, as runAs StandAlone-User to Create Opportunity
            insert opp;
        }

       // Check the and confirm no team Memeber is added in Oppo team as thsi user dont have a manager or reporting user
       List<OpportunityTeamMember> OppAssert = [Select ID, Opportunity.ID from OpportunityTeamMember where Opportunity.Id = :opp.Id Limit 1];
       System.assertEquals(True, OppAssert.isEmpty());
    }

    @IsTest static void OppCrtMangerUsr1(){//2. Opp created by a Manager user with 1 Employee to Report  to him --- Add Employee to OpportunityTeam as SalesRep  
        Opportunity opp                  = new Opportunity();
        opp.Name                         = 'Test opp by MangerUser';
        opp.CloseDate                    = Date.today() + 30;
        opp.StageName                    = 'Prospecting';

        User ManagerToCreate             = initTestUser('robiadmincml'); //Create a manager user
        insert ManagerToCreate;

        User userToCreate                = initTestUser('robiadmincml1'); // Create an Employee
        userToCreate.ManagerId           = ManagerToCreate.Id;            // Assign Manager to an Employee
        insert userToCreate;

        system.runAs(ManagerToCreate ){
            //opp.OwnerId                = ManagerToCreate.Id;            // No need, as runAs Manager-User to Create Opportunity
            insert opp;
        }

        // Check the Employee added in Opp team role as SalesRep
        List<OpportunityTeamMember> OppAssert = [Select ID, Opportunity.ID, TeamMemberRole from OpportunityTeamMember where Opportunity.Id = :opp.Id Limit 1];
        System.assertEquals('Sales Rep', OppAssert.get(0).TeamMemberRole); 
    }

    @IsTest static void OppCrtEmpUsr1(){ //3. Opp created by an Emp user with 1 Manager above him --- Add Manager to OpportunityTeam as SalesManager  
        Opportunity opp                     = new Opportunity();
        opp.Name                            = 'Testing1';
        opp.CloseDate                       = Date.today() + 30;
        opp.StageName                       = 'Prospecting';

        User ManagerToCreate                = initTestUser('robiadmincml'); //Create a manager user
        insert ManagerToCreate;

        User userToCreate                   = initTestUser('robiadmincml1'); // Create an Employee
        userToCreate.ManagerId              = ManagerToCreate.Id;            // Assign Manager to an Employee
        insert userToCreate;

        system.runAs(userToCreate){
            //opp.OwnerId                       = userToCreate.Id;          // No need, as runAs Employee-User to Create Opportunity
            insert opp;
        }        

       // Check the Manager is added in Opp team role as SalesManager
       List<OpportunityTeamMember> OppAssert = [Select ID, Opportunity.ID, TeamMemberRole from OpportunityTeamMember where Opportunity.Id = :opp.Id Limit 1];
       System.assertEquals('Sales Manager', OppAssert.get(0).TeamMemberRole);
    }

    @IsTest static void OppCrtMngrEmpUsr1(){ //4. Opp created by an Manager-Emp user with 1 Manager above & 1 Employee Down to report to him 
                                            //---two Entries to OpportunityTeam Memebr -   Add Manager as SalesManager &  Add Employee as SalesRep    
        Opportunity opp                     = new Opportunity();
        opp.Name                            = 'Testing1';
        opp.CloseDate                       = Date.today() + 30;
        opp.StageName                       = 'Prospecting';

        User ManagerToCreate                = initTestUser('robiadmincml'); //Create a manager user
        insert ManagerToCreate;

        User mngrEmpuserToCreate            = initTestUser('robiadmincmlx'); // Create a Manager-Employee user
        mngrEmpuserToCreate.ManagerId       = ManagerToCreate.Id;            // Assign Manager to an Employee
        insert mngrEmpuserToCreate ;

        User userToCreate                   = initTestUser('robiadmincml1'); // Create an Employee
        userToCreate.ManagerId              = mngrEmpuserToCreate .Id;       // Assign Manager-Employee user to Employee
        insert userToCreate;     

        system.runAs(mngrEmpuserToCreate){
            //opp.OwnerId                   = mngrEmpuserToCreate.Id;          // No need, as runAs Manager-Employee user to Create Opportunity
            insert opp;
    }        

    // Check the Manager is added in Opp team role as SalesManager
    List<OpportunityTeamMember> OppAssertMgnr = [Select ID, Opportunity.ID, TeamMemberRole from OpportunityTeamMember 
                                                    where Opportunity.Id = :opp.Id and User.Id = :ManagerToCreate.Id];
    System.assertEquals('Sales Manager', OppAssertMgnr.get(0).TeamMemberRole);

     // Check the Employee is added in Opp team role as SalesRep
    List<OpportunityTeamMember> OppAssertEmp = [Select ID, Opportunity.ID, TeamMemberRole, User.Id from OpportunityTeamMember 
                                                    where Opportunity.Id = :opp.Id and User.Id = :userToCreate.Id];
    System.assertEquals('Sales Rep', OppAssertEmp.get(0).TeamMemberRole);
  }

  //User Creation template
  Public Static user initTestUser(String userName){
        Profile userPrf         = [select id from profile where name='System Administrator'];
        User    userCrt         = new User(emailencodingkey     = 'UTF-8',
                                            languagelocalekey   = 'en_US',
                                            localesidkey        = 'en_US',
                                            timezonesidkey      = 'America/Los_Angeles',
                                            alias               = 'Tstr', 
                                            lastname            = userName,
                                            email               = userName + '@testorg.com',
                                            profileid           = userPrf.Id, 
                                            username            = userName + '@testorg.com');
        return userCrt;
  }
}

Best Answer

Above code seems to be fine, but you need to add Test.startTest & Test.stopTest in testmethod before system.runAs. And you can also use testMethod instead of @isTest annotation for method definition.

For e.g.

static testMethod void unitTest() {

    Opportunity opp = new Opportunity();
    opp.Name = 'Testing1';
    opp.CloseDate = Date.today() + 30;
    opp.StageName = 'Prospecting';

    User userToCreate = initTestUser('robiadmincml1');
    insert userToCreate;
    Test.startTest();
        system.runAs(userToCreate){ 
            //opp.OwnerId = userToCreate.Id; //No need, as runAs StandAlone-User to Create Opportunity
            insert opp;
        }
    Test.stopTest();
    // Check the and confirm no team Memeber is added in Oppo team as thsi user dont have a manager or reporting user
    List<OpportunityTeamMember> OppAssert = [Select ID, Opportunity.ID from OpportunityTeamMember where Opportunity.Id = :opp.Id Limit 1];
    System.assertEquals(True, OppAssert.isEmpty());
}
Related Topic