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
Swaroopa Akula 1Swaroopa Akula 1 

test class for portaluser creation



    Usage: This trigger is used to send mail to Portal User which are created 
           from Self Registration Object
     
****************************************************************************/
trigger PortalUserCreation on Self_Register_User_Request__c (before update) {

    
    String DUMMY_ACCOUNT  = 'Dummy Account' ;
    List<Contact> conListToInsert = new List<Contact>();
    
    Map<Id, String> emailMap = new Map<Id, String>();
    Map<Id, Self_Register_User_Request__c> dummyMap = new Map<Id, Self_Register_User_Request__c>();
    
    for(Self_Register_User_Request__c sr :trigger.new) { 
        System.debug('here is FN: '+sr.FirstName__c);
        System.debug('here is FN: '+sr.LastName__c);
        System.debug('here is FN: '+sr.Email__c);
        System.debug('here is FN: '+sr.AccountName__c);
        if(sr.FirstName__c == null || sr.LastName__c == null || sr.Email__c == null)  
            continue;      
           if(sr.Is_it_Approved__c  = TRUE){
            if(sr.AccountName__c != null ){
                Contact conRecord = new Contact(
                    FirstName = sr.FirstName__c,
                    LastName = sr.LastName__c,
                    Email = sr.Email__c,
                    AccountId = sr.AccountName__c
                );              
                System.debug('adding contact from line 36');
                conListToInsert.add(conRecord); 
            }
           
            if(sr.Email__c != null){
                emailMap.put(sr.Id, sr.Email__c);           
            }
            
            dummyMap.put(sr.Id, sr);                    
        }
    }
    //create Portal User
    if(conListToInsert != null && conListToInsert.size() > 0) {
        insert conListToInsert;
        List<Profile> pList = [select id from Profile where Name = 'Partner Community '];
        if(!pList.isEmpty()){
            Profile p = pList[0];
            List<User> userListToInsert = new List<User>();
            for(Contact con :conListToInsert) {             
                String alias1 = '';
                if(con.FirstName.length() >= 0)
                    alias1 = con.FirstName.substring(0,1);
                    
                String alias2 = '';
                if(con.LastName.length() >= 4){
                    alias2 = con.LastName.substring(0, 4);        
                }else{
                    alias2 = con.LastName;
                }
                String alias = alias1 + alias2;
                User u = new User(
                    Alias = alias, 
                    Email = con.Email,
                    EmailEncodingKey = 'UTF-8', 
                    FirstName = con.FirstName,
                    LastName = con.LastName, 
                    LanguageLocaleKey = 'en_US', 
                    LocalesIdKey = 'en_US', 
                    ProfileId = p.Id, 
                    ContactId = con.id,
                    TimeZonesIdKey = 'America/Los_Angeles', 
                    UserName = con.Email
                );
                Database.DMLOptions dmo = new Database.DMLOptions();
                dmo.EmailHeader.triggerUserEmail = true;
                u.setOptions(dmo);
                userListToInsert.add(u);
            }
                
            Database.SaveResult[] results = database.insert(userListToInsert, false);
            for(Database.SaveResult sr :results){
               if(!sr.isSuccess()){
                  Database.Error err = sr.getErrors()[0];
                  throw new CustomException(err.getMessage());
                 /* break;*/
               }
            }                       
        }        
    }  
    
   
    //define your custom exception
    public class CustomException extends Exception{}
    
}
Raj VakatiRaj Vakati
Try this
 
@isTest
private class PortalUserCreationTest {

    static TestMethod void myUnitTest()
    {
        Profile profile1 = [Select Id from Profile where name = 'System Administrator'];
       System.debug('What is the profile id ' + profile1);
       UserRole portalRole = [Select Id From UserRole Where PortalType = 'None' Limit 1];
       date tDate = date.today();
       date uDate = Date.today().addDays(30);
        
         User u = new User(
            UserRoleId = portalRole.Id,
            ProfileId = profile1.Id,
            Username = 'testtermsconditions1234423@demooo.com',
            Alias = 'batman',
            Email='testtermsconditions1234423@demooo.com',
            EmailEncodingKey='UTF-8',
            Firstname='Bruce',
            Lastname='Wayne',
            LanguageLocaleKey='en_US',
            LocaleSidKey='en_US',
            TimeZoneSidKey='America/Chicago');
            insert u;
          
        
       
        
        System.runas(u) {
        
      
            
        
        
        Test.startTest();
		  Account acc = new Account();
            acc.Name ='Test1';
            acc.Account_Type__c = 'Reseller';
            acc.New_Account_Source__c = 'Advertisement';

        insert acc;
            Self_Register_User_Request__c  selfregister =  new Self_Register_User_Request__c ();
                                                                       selfregister.FirstName__c='Sree';
                                                                       selfregister.LastName__c='Chandra';
                                                                       selfregister.Email__c='Test@gmail.com';
                                                                       selfregister.Company_web_site__c='WWW.DST.com';
                                                                       selfregister.Company__c='DST';
                                                                       selfregister.AccountName__c= acc.id;
                                                                        selfregister.Is_it_Approved__c  =false ; 
                                                                       insert selfregister ;
                                                                     
            
              selfregister.Is_it_Approved__c  =true ; 
			  update selfregister ;
        Test.stopTest();
        }
    }
}

 
Swaroopa Akula 1Swaroopa Akula 1
If I using the update selfregister; it is giving me an error:


[View]
0:02
PortalUserCreationTest
myUnitTest
Fail
System.DmlException: Update failed. First exception on row 0 with id a591g00000087oyAAA; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, PortalUserCreation: execution of BeforeUpdate caused by: PortalUserCreation.CustomException: Duplicate Username.<br>The username already exists in this or another Salesforce organization. Usernames must be unique across all Salesforce organizations. To resolve, use a different username (it doesn't need to match the user's email address). Trigger.PortalUserCreation: line 85, column 1: []
Raj VakatiRaj Vakati
Change it as below
@isTest
private class PortalUserCreationTest {

    static TestMethod void myUnitTest()
    {
        Profile profile1 = [Select Id from Profile where name = 'System Administrator'];
       System.debug('What is the profile id ' + profile1);
       UserRole portalRole = [Select Id From UserRole Where PortalType = 'None' Limit 1];
       date tDate = date.today();
       date uDate = Date.today().addDays(30);
        
         User u = new User(
            UserRoleId = portalRole.Id,
            ProfileId = profile1.Id,
            Username = 'testtermsc123123onditions1234423@mycomany.com',
            Alias = 'batman',
            Email='testtermscon123dit123ions1234423@mycomany.com',
            EmailEncodingKey='UTF-8',
            Firstname='Bruce',
            Lastname='Wayne',
            LanguageLocaleKey='en_US',
            LocaleSidKey='en_US',
            TimeZoneSidKey='America/Chicago');
            insert u;
          
        
       
        
        System.runas(u) {
        
      
            
        
        
        Test.startTest();
		  Account acc = new Account();
            acc.Name ='Test1';
            acc.Account_Type__c = 'Reseller';
            acc.New_Account_Source__c = 'Advertisement';

        insert acc;
            Self_Register_User_Request__c  selfregister =  new Self_Register_User_Request__c ();
                                                                       selfregister.FirstName__c='Sree';
                                                                       selfregister.LastName__c='Chandra';
                                                                       selfregister.Email__c='Test@gmail.com';
                                                                       selfregister.Company_web_site__c='WWW.DST.com';
                                                                       selfregister.Company__c='DST';
                                                                       selfregister.AccountName__c= acc.id;
                                                                        selfregister.Is_it_Approved__c  =false ; 
                                                                       insert selfregister ;
                                                                     
            
              selfregister.Is_it_Approved__c  =true ; 
			  update selfregister ;
        Test.stopTest();
        }
    }
}

 
Swaroopa Akula 1Swaroopa Akula 1
I have used the same above code. but still getting the same error.




@isTest
private class PortalUserCreationTest {

    static TestMethod void myUnitTest()
    {
        Profile profile1 = [Select Id from Profile where name = 'System Administrator'];
       System.debug('What is the profile id ' + profile1);
       UserRole portalRole = [Select Id From UserRole Where PortalType = 'None' Limit 1];
       date tDate = date.today();
       date uDate = Date.today().addDays(30);
        
         User u = new User(
            UserRoleId = portalRole.Id,
            ProfileId = profile1.Id,
            Username = 'testtermsc123123onditions1234423@mycomany.com',
            Alias = 'batman',
            Email='testtermscon123dit123ions1234423@mycomany.com',
            EmailEncodingKey='UTF-8',
            Firstname='Bruce',
            Lastname='Wayne',
            LanguageLocaleKey='en_US',
            LocaleSidKey='en_US',
            TimeZoneSidKey='America/Chicago');
            insert u;
          
        
       
        
        System.runas(u) {
        
        Account acc = new Account();
            acc.Name ='Test1';
            acc.Account_Type__c = 'Reseller';
            acc.New_Account_Source__c = 'Advertisement';

        insert acc;
            
        
        
        Test.startTest();
            Self_Register_User_Request__c  selfregister =  new Self_Register_User_Request__c ();
                                                                       selfregister.FirstName__c='Sree';
                                                                       selfregister.LastName__c='Chandra';
                                                                       selfregister.Email__c='Test@gmail.com';
                                                                       selfregister.Company_web_site__c='WWW.DST.com';
                                                                       selfregister.Company__c='DST';
                                                                       selfregister.AccountName__c= acc.id;
                                                                        selfregister.Is_it_Approved__c  =False ; 
                                                                       insert selfregister ;
            
            
            
                                                                        selfregister.AccountName__c= acc.id;
                                                                        selfregister.Is_it_Approved__c  =true ; 
                                                                       update selfregister ;                                                      
                                                                       //selfregister.Is_it_Approved__c  =true ; 
                                                                       //selfregister.Status__c='New';
                                                                      // update selfregister ;
                                                                       
                                                                       
            
            
        Test.stopTest();
        }
    }
}
Swaroopa Akula 1Swaroopa Akula 1
Error MessageSystem.DmlException: Update failed. First exception on row 0 with id a591g00000087pIAAQ; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, PortalUserCreation: execution of BeforeUpdate

caused by: PortalUserCreation.CustomException: Duplicate Username.<br>The username already exists in this or another Salesforce organization. Usernames must be unique across all Salesforce organizations. To resolve, use a different username (it doesn't need to match the user's email address). 

Trigger.PortalUserCreation: line 85, column 1: []
Stack TraceClass.PortalUserCreationTest.myUnitTest: line 55, column 1
Swaroopa Akula 1Swaroopa Akula 1
Can someone please help me on this