+ Start a Discussion
Tristan PTristan P 

Writing a Test Class for an Apex Trigger

Hi guys,

I'm relatively new to Apex and am struggling a bit with a Test Class - I hope you can help!

Here is my Apex Trigger to create new Community users when Contacts are inserted:
 
trigger NewCommUser on Contact (After insert) {
     
     if(Trigger.isInsert){ 
     
         for(Contact co : trigger.new){
            Contact con = [select id,email,firstName,lastname,accountId,Do_Not_Grant_Community_Access__c,Account_Status_Text__c from Contact where Id =:co.Id];         
            Database.DMLOptions dmo = new Database.DMLOptions();
            dmo.EmailHeader.triggerUserEmail = false;       
            dmo.EmailHeader.triggerOtherEmail = false;
            dmo.EmailHeader.triggerAutoResponseEmail = false;       
            dmo.optAllOrNone = false;

            // Create Community Hub user
            List<User> unames = [select username from user where email =:con.email LIMIT 1];
            List<Contact> accountstatus = [select id from contact where Account_Status_Text__c = 'Signed-Up' and Id=:co.Id LIMIT 1];
            
            string userAlias;
            if (con.firstName.length() > 8)
            userAlias = con.firstName.substring(0,8); else userAlias = con.firstName;    
            
            if(unames.isEmpty() && !con.Do_Not_Grant_Community_Access__c && accountstatus.Size()>0){
                string nick = con.email!=null?con.email.substring(0, con.email.indexOf('@')):''; 
                nick += Datetime.now().getTime();
                User newUser1 = new User(alias=userAlias, email = con.email, emailencodingkey = 'UTF-8', firstname = con.firstName, lastname = con.lastname, languagelocalekey = 'en_US',localesidkey = 'en_GB',contactId = con.Id,timezonesidkey = 'Europe/London',username = con.email,CommunityNickname = nick,ProfileId ='00e58000000NkUd', IsActive = true);
                newUser1.setOptions(dmo); insert newUser1;
            }
         }
     }
}

And here is my Test Class:
 
@isTest
public class NewCommUserTest {
    
    @Testsetup
    static void dataSetup() {
        
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
    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 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=uniqueName + '@test' + orgId + '.org');
        
        u.UserRoleId=[select Id from UserRole where Name='CEO'].Id;
        
        //System.debug([select Id from UserRole where Name='CEO']);
        insert u;
       
        System.runAs(u) {
            Account a = new Account();
            a.Name = 'Test Account';
            insert a;                 
            
            Contact c = new Contact();
            c.LastName = ' Contact1';
            c.FirstName = 'test';
            
            c.Account_Status_Text__c = 'Signed-Up';
            c.Email = 'standarduser1@testorg.com';
            c.Do_Not_Grant_Community_Access__c = true;
            c.AccountId = a.Id;
            insert c;
            
            c.Do_Not_Grant_Community_Access__c = FALSE;
            update c;
        }
        
        
    }    
    
    @isTest static void testUpdateOrgForNewBusiness2() { 
        
        Account a = [select Id from Account limit 1];
        Contact c = new Contact();
        c.LastName = 'Contact1234';
        c.FirstName = 'test';
        
        c.Account_Status_Text__c = 'Signed-Up';
        c.Email = 'standarduser1@testorg.com';
        c.Do_Not_Grant_Community_Access__c = true;
        c.Account = a;
        insert c;
        
        c.Do_Not_Grant_Community_Access__c = FALSE;
        c.LastName = 'Contact1';
        update c;
        
    }
    
}

I'm currently at 73% coverage but so far am having trouble with this part of my Trigger:
 
string nick = con.email!=null?con.email.substring(0, con.email.indexOf('@')):''; 
nick += Datetime.now().getTime();
User newUser1 = new User(alias=userAlias, email = con.email, emailencodingkey = 'UTF-8', firstname = con.firstName, lastname = con.lastname, languagelocalekey = 'en_US',localesidkey = 'en_GB',contactId = con.Id,timezonesidkey = 'Europe/London',username = con.email,CommunityNickname = nick,ProfileId ='00e58000000NkUd', IsActive = true);
newUser1.setOptions(dmo); insert newUser1;

Can anyone please help me with how I can add this in my Test Class?

Thanks,

Tristan

 
Best Answer chosen by Tristan P
Raj VakatiRaj Vakati
Try this ..you have to insert contact like this
 
Contact c = new Contact();
            c.LastName = ' Contact1';
            c.FirstName = 'test';
            c.Account_Status_Text__c = 'Signed-Up';
            c.Email = 'standarduser@testorg.com';
            c.Do_Not_Grant_Community_Access__c = true;
            c.AccountId = a.Id;
            insert c;

Complete code
 
@isTest
public class NewCommUserTest {
    
    @Testsetup
    static void dataSetup() {
        
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
    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 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=uniqueName + '@test' + orgId + '.org');
        
        u.UserRoleId=[select Id from UserRole where Name='CEO'].Id;
        
        //System.debug([select Id from UserRole where Name='CEO']);
        insert u;
       
        System.runAs(u) {
            Account a = new Account();
            a.Name = 'Test Account';
            insert a;                 
            
            Contact c = new Contact();
            c.LastName = ' Contact1';
            c.FirstName = 'test';
            c.Account_Status_Text__c = 'Signed-Up';
            c.Email = 'standarduser@testorg.com';
            c.Do_Not_Grant_Community_Access__c = true;
            c.AccountId = a.Id;
            insert c;
            
			Contact c1 = new Contact();
            c1.LastName = ' Contact1';
            c1.FirstName = 'test';
            c1.Account_Status_Text__c = 'Signed-Up';
            c1.Email = 'standarduser@testorg.com';
            c1.Do_Not_Grant_Community_Access__c = true;
            c1.AccountId = a.Id;
            insert c1;
            
			
        }
        
        
    }    
    
    @isTest static void testUpdateOrgForNewBusiness2() { 
        
        Account a = [select Id from Account limit 1];
        Contact c = new Contact();
        c.LastName = 'Contact1234';
        c.FirstName = 'test';
        
        c.Account_Status_Text__c = 'Signed-Up';
        c.Email = 'standarduser1@testorg.com';
        c.Do_Not_Grant_Community_Access__c = true;
        c.Account = a;
        insert c;
        
        c.Do_Not_Grant_Community_Access__c = FALSE;
        c.LastName = 'Contact1';
        update c;
        
    }
    
}

 

All Answers

Raj VakatiRaj Vakati
Try this ..you have to insert contact like this
 
Contact c = new Contact();
            c.LastName = ' Contact1';
            c.FirstName = 'test';
            c.Account_Status_Text__c = 'Signed-Up';
            c.Email = 'standarduser@testorg.com';
            c.Do_Not_Grant_Community_Access__c = true;
            c.AccountId = a.Id;
            insert c;

Complete code
 
@isTest
public class NewCommUserTest {
    
    @Testsetup
    static void dataSetup() {
        
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
    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 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=uniqueName + '@test' + orgId + '.org');
        
        u.UserRoleId=[select Id from UserRole where Name='CEO'].Id;
        
        //System.debug([select Id from UserRole where Name='CEO']);
        insert u;
       
        System.runAs(u) {
            Account a = new Account();
            a.Name = 'Test Account';
            insert a;                 
            
            Contact c = new Contact();
            c.LastName = ' Contact1';
            c.FirstName = 'test';
            c.Account_Status_Text__c = 'Signed-Up';
            c.Email = 'standarduser@testorg.com';
            c.Do_Not_Grant_Community_Access__c = true;
            c.AccountId = a.Id;
            insert c;
            
			Contact c1 = new Contact();
            c1.LastName = ' Contact1';
            c1.FirstName = 'test';
            c1.Account_Status_Text__c = 'Signed-Up';
            c1.Email = 'standarduser@testorg.com';
            c1.Do_Not_Grant_Community_Access__c = true;
            c1.AccountId = a.Id;
            insert c1;
            
			
        }
        
        
    }    
    
    @isTest static void testUpdateOrgForNewBusiness2() { 
        
        Account a = [select Id from Account limit 1];
        Contact c = new Contact();
        c.LastName = 'Contact1234';
        c.FirstName = 'test';
        
        c.Account_Status_Text__c = 'Signed-Up';
        c.Email = 'standarduser1@testorg.com';
        c.Do_Not_Grant_Community_Access__c = true;
        c.Account = a;
        insert c;
        
        c.Do_Not_Grant_Community_Access__c = FALSE;
        c.LastName = 'Contact1';
        update c;
        
    }
    
}

 
This was selected as the best answer
Tristan PTristan P
This is great, thank you very much!