0

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;
  }
}
3

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());
}
| improve this answer | |
  • @RC thnx for your reply. I just googled the usage of start and stop test methods but couldn't find a hard rule or thumb rule regarding when to use it. So can I use it always in my test methods/class whenever a DML operation is done like above always as a best practice? – Robert Thomas Feb 8 '17 at 12:57
  • @RC.. also is there any significance on using testmethod keyword instead of isTest. I read it here in salesforcestack as salesforce.stackexchange.com/questions/739/… ---"One advantage to creating a separate class for testing as opposed to adding test methods to an existing class is that classes defined with isTest don't count against your organization limit of 3 MB for all Apex code." So IsTest is preferable, Is it? – Robert Thomas Feb 8 '17 at 13:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.