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
sudhirn@merunetworks.comsudhirn@merunetworks.com 

Test Class for Trigger for user role check

Hi, 

  Please help me to write a test class trigger for below code 
 
trigger roleCheck on User (before insert, before update){
    Set<String> roleNameSet=new Set<String>{'Finance Approver' , 'GHC Approver ' , 'Program Administrator'};
	Set<Id> userRoleIdSet=new Set<Id>();
	for(userRole useRol :[SELECT id  FROM UserRole  WHERE Name IN: roleNameSet]){
		userRoleIdSet.add(useRol.Id);
	}
	if(trigger.isInert){
		for(User usr : Trigger.new){
			if(userRoleIdSet.contains(usr.UserRoleId)){
				usr.adderror('Role Aleready Assigned, select new Role');
			}
		}
	}if(Trigger.isUpdate){
		for(User usr : Trigger.new){
			if(userRoleIdSet.contains(usr.UserRoleId) && usr.UserRoleId != Trigger.oldMap.get(usr.Id).UserRoleId ){
				usr.adderror('Role aleready assigned, select new Role');
			}
		}
	}
}


Thanks

Sudhir

Best Answer chosen by sudhirn@merunetworks.com
Arunkumar RArunkumar R
Hi Sudhir,

Try out the below test class. One class for utilty class for creating user another one contains test methods,



 
@isTest
public class TestUserUtil
{
    public static User createTestUser(Id roleId, Id profID, String fName, String lName)
    {
        String orgId = UserInfo.getOrganizationId();
        String dateString = String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','');
       
        Integer randomInt = Integer.valueOf(math.rint(math.random()*1000000));
        String uniqueName = orgId + dateString + randomInt;
        User tuser = new User(  firstname = fName,
                                lastName = lName,
                                email = uniqueName + '@test' + orgId + '.org',
                                Username = uniqueName + '@test' + orgId + '.org',
                                EmailEncodingKey = 'ISO-8859-1',
                                Alias = uniqueName.substring(18, 23),
                                TimeZoneSidKey = 'America/Los_Angeles',
                                LocaleSidKey = 'en_US',
                                LanguageLocaleKey = 'en_US',
                                ProfileId = profId,
                                UserRoleId = roleId);
        return tuser;
    }
}

@isTest
private class RoleCheckTestClass
{
    static testMethod void insertUser1()
    {
        Profile pf = [SELECT Id FROM Profile WHERE Name = 'System Administrator'];
       
        UserRole ur = new UserRole(Name = 'Finance Approver');
        insert ur;
        User usr = TestUserUtil.createTestUser(ur.Id, pf.Id, 'Test FirstName', 'Test LastName');
        try
        {
            insert usr;
         }
         Catch(DMLException e)
         {
         
         }
       
    }
    
     static testMethod void insertUser2()
    {
        Profile pf = [SELECT Id FROM Profile WHERE Name = 'System Administrator'];
       
        UserRole ur = new UserRole(Name = 'Finance');
        insert ur;
        User usr = TestUserUtil.createTestUser(ur.Id, pf.Id, 'Test FirstName', 'Test LastName');
        insert usr;
        
        UserRole ur1 = new UserRole(Name = 'Finance Approver');
        insert ur1;
        usr.UserRoleId = ur1.Id;
        
        try
        {
        update usr;
        }
        catch(Exception e)
        {
        
        }
       
    }
}

All Answers

James LoghryJames Loghry
Sudhir,

Please see the following document from developer.salesforce.com.  There's tips for writing your first trigger, along with writing a test class for said trigger.  https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_qs_HelloWorld.htm.

Also, please keep in mind that we're here to help, but not do your work for you at the same time.  If you have issues writing the test class based on the example in the link above, then you're more than welcome to come back and ask for help on it, but please read up a little bit first before asking the community to write your test class for you.

Thanks.
Arunkumar RArunkumar R
Hi Sudhir,

Try out the below test class. One class for utilty class for creating user another one contains test methods,



 
@isTest
public class TestUserUtil
{
    public static User createTestUser(Id roleId, Id profID, String fName, String lName)
    {
        String orgId = UserInfo.getOrganizationId();
        String dateString = String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','');
       
        Integer randomInt = Integer.valueOf(math.rint(math.random()*1000000));
        String uniqueName = orgId + dateString + randomInt;
        User tuser = new User(  firstname = fName,
                                lastName = lName,
                                email = uniqueName + '@test' + orgId + '.org',
                                Username = uniqueName + '@test' + orgId + '.org',
                                EmailEncodingKey = 'ISO-8859-1',
                                Alias = uniqueName.substring(18, 23),
                                TimeZoneSidKey = 'America/Los_Angeles',
                                LocaleSidKey = 'en_US',
                                LanguageLocaleKey = 'en_US',
                                ProfileId = profId,
                                UserRoleId = roleId);
        return tuser;
    }
}

@isTest
private class RoleCheckTestClass
{
    static testMethod void insertUser1()
    {
        Profile pf = [SELECT Id FROM Profile WHERE Name = 'System Administrator'];
       
        UserRole ur = new UserRole(Name = 'Finance Approver');
        insert ur;
        User usr = TestUserUtil.createTestUser(ur.Id, pf.Id, 'Test FirstName', 'Test LastName');
        try
        {
            insert usr;
         }
         Catch(DMLException e)
         {
         
         }
       
    }
    
     static testMethod void insertUser2()
    {
        Profile pf = [SELECT Id FROM Profile WHERE Name = 'System Administrator'];
       
        UserRole ur = new UserRole(Name = 'Finance');
        insert ur;
        User usr = TestUserUtil.createTestUser(ur.Id, pf.Id, 'Test FirstName', 'Test LastName');
        insert usr;
        
        UserRole ur1 = new UserRole(Name = 'Finance Approver');
        insert ur1;
        usr.UserRoleId = ur1.Id;
        
        try
        {
        update usr;
        }
        catch(Exception e)
        {
        
        }
       
    }
}
This was selected as the best answer