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
Harsha ShriHarsha Shri 

Need help in User object Test class

 Hi All,
I have written apex class related to user object.
I am very new to test classes. Can someone please help me with this. Following are my classes
public class UserController {
    
    public static List <UserWrapper> fetchUser(String searchKeyWord,String sortField,Boolean isAsc) {
        
        profile p =[Select Name from Profile where Id =: userinfo.getProfileid()];
        List<UserWrapper> UserRec = new List<UserWrapper>();
        String searchKey = '%'+searchKeyWord + '%';
        List < User > returnList = new List < User > ();
        List < User > lstOfUser=new List < User > ();
        
        List<String> profiles= new List<String>();
        String sSoql='';   
        String emailRegex = '^[a-zA-Z0-9._|\\\\%#~`=?&/$^*!}{+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}$';
        Pattern MyPattern = Pattern.compile(emailRegex);
        Matcher MyMatcher = MyPattern.matcher(searchKeyWord);
        String pn='Label3';
        profiles= pn.split(',');
        if(p.Name.equals('Customer Portal Manager')){
            
            List<Contact> con = [select ID from Contact where AccountID in(select id from Account)];
           if (!MyMatcher.matches()){
                sSoql='select Name, Email from User where Name LIKE \''+ searchKey+'\' and IsActive = true and Profile.Name in :profiles and Id != \''+Userinfo.getUserId()+'\' and ContactID in:con'; 
                
              }else{
                sSoql='select Name, Email from User where Email LIKE \''+ searchKey+'\' and IsActive = true and Profile.Name in :profiles and Id != \''+Userinfo.getUserId()+'\' and ContactID in:con';   
                
            }
        }
        else{
            
                if (!MyMatcher.matches()){
                    sSoql='select Name, Email from User where Name LIKE \''+ searchKey+'\' and IsActive = true and Profile.Name in :profiles and Id != \''+Userinfo.getUserId()+'\''; 
                }     
                else{
                    sSoql='select Name, Email from User where Email LIKE \''+ searchKey+'\' and IsActive = true and Profile.Name in :profiles and Id != \''+Userinfo.getUserId()+'\''; 
                    
                }
        }
            if (sortField != '' && sortField != Null) {
                sSoql += ' order by ' + sortField;
               
                if(isAsc!=Null)
                {
                    if (isAsc) {
                        sSoql += ' asc NULLS LAST';
                    } else {
                        sSoql += ' desc';
                    }
                }
            }
            try
            {
                
                lstOfUser= Database.query(sSoql);
                
            }Catch(Exception e)
            {
                System.debug('exception in user'+e);
            }
            for (User acc: lstOfUser) {
                UserWrapper user_rec = new UserWrapper();
                user_rec.UserEmail=acc.Email;
                user_rec.Name=acc.Name;
                user_rec.userID=acc.Id;
                user_rec.isSelected=true;
                UserRec.add(user_rec);
            }
            
            return UserRec;
        
    }  
   
    public static String getUserName(String UserID){
        return [select name from User where ID=:UserID].Name;
    }
   
    public static List<UserWrapper> performAction(String userRecords,List<UserWrapper> selectedUsers){
        List<UserWrapper> storeresult = new List<userWrapper>();
        if(!string.isBlank(userRecords))  {
            List<UserWrapper> lstUserRecords = 
                (List<UserWrapper>)
                System.JSON.deserialize(userRecords,List<UserWrapper>.class);
           
            for(UserWrapper objPositionRecords:lstUserRecords)
            {
                if(objPositionRecords.isSelected)
                { storeresult.add(objPositionRecords);
                
                }
            }
            selectedUsers.addAll(storeresult);
          
        }
        return selectedUsers;
        
    } 

    public static List<UserWrapper> removeUsers(String removeUsers){
        List<UserWrapper> remove_Users = new List<userWrapper>();
        if(!string.isBlank(removeUsers))  {
            List<UserWrapper> rmvUserRecords = 
                (List<UserWrapper>)
                System.JSON.deserialize(removeUsers,List<UserWrapper>.class);
            
            for(UserWrapper objPositionRecords:rmvUserRecords)
            {
                if(!objPositionRecords.isSelected)
                { remove_Users.add(objPositionRecords);
                 
                }
            }
           
        }
        return remove_Users;
        
        
        
    }
}
 
public class UserWrapper {
     public boolean isSelected;
    public String UserEmail;
     public String Name;
     public String userID;
    
    public UserWrapper()
    {
        isSelected = false;
        UserEmail='';
        Name = '';
    }    
}

Please help me in wrtting test class for this.
Thanks in Advance​
Best Answer chosen by Harsha Shri
sfdcMonkey.comsfdcMonkey.com
1+ to Raj, but you have need to serialize wrapper class List while passing it to method params :

try following code, this will give you more then 75% coverge 
@isTest
public class UserController_Test {
    
    public static testMethod void testRunAs() {
        // Setup test data
        // Create a unique UserName
        String uniqueUserName = 'standarduserGFASFa@testorg.com';
        // This code runs as the system user
        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
        User u = new User(Alias = 'standt', Email='standardus123123er@testorg.com',
                          EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
                          LocaleSidKey='en_US', ProfileId = p.Id,
                          TimeZoneSidKey='America/Los_Angeles',
                          UserName=uniqueUserName);
        
        insert u ;
        UserController uuu = new UserController();
    
        UserWrapper testWrap=new UserWrapper();
        testWrap.isSelected = true;
        testWrap.UserEmail = u.email ; 
        testWrap.Name =u.Name ; 
        testWrap.userID = u.UserName ; 
        
        List<UserWrapper> dmeo12 =new List<UserWrapper>(); 
        dmeo12.add(testWrap);
        UserController.fetchUser('Testing','Name' ,false);
        UserController.removeUsers(JSON.serialize(dmeo12));
        UserController.getUserName(u.Id);
        UserController.performAction(JSON.serialize(dmeo12), dmeo12);
    }
}

Thanks, let us know if it helps you 

All Answers

Gustavo BertolinoGustavo Bertolino

First, I recommend you to accomplish Test Class construction's trailhead to help you to understand how to make it and, more important, to understand how it works. Then do search beyond Google and take a look at questions and inquiries here in SF Dev Forum which are related to what you're asking for. And finally collect all things you've done and researched since then and show us what you've made until now in terms of Test Classes for those Classes above. It will help us to help you much better. 

Tips about Test Classes. Basically you have to use Assert methods in your Test Classes to grasp values and compare them to the value you've passed in. Once you've done it, you can sophiscated it in order to achieve 75% recovery of your code.

Raj VakatiRaj Vakati
@isTest
public class UserController_Test {
    
    public static testMethod void testRunAs() {
        // Setup test data
        // Create a unique UserName
        String uniqueUserName = 'standarduserGFASFa@testorg.com';
        // This code runs as the system user
        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
        User u = new User(Alias = 'standt', Email='standardus123123er@testorg.com',
                          EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
                          LocaleSidKey='en_US', ProfileId = p.Id,
                          TimeZoneSidKey='America/Los_Angeles',
                          UserName=uniqueUserName);
        
        insert u ;
        UserController uuu = new UserController();
     UserWrapper testWrap=new UserWrapper();
        testWrap.isSelected = true;
        testWrap.UserEmail = u.email ; 
        testWrap.Name =u.Name ; 
        testWrap.userID = u.UserName ; 
        List<UserWrapper> dmeo12 =new List<UserWrapper>(); 
        dmeo12.add(testWrap);
        UserController.fetchUser('Testing','Name' ,false);
        UserController.removeUsers(u.UserName);
        UserController.getUserName(u.UserName);
        UserController.performAction(u.Id, dmeo12);
        
    }
}

 
sfdcMonkey.comsfdcMonkey.com
1+ to Raj, but you have need to serialize wrapper class List while passing it to method params :

try following code, this will give you more then 75% coverge 
@isTest
public class UserController_Test {
    
    public static testMethod void testRunAs() {
        // Setup test data
        // Create a unique UserName
        String uniqueUserName = 'standarduserGFASFa@testorg.com';
        // This code runs as the system user
        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
        User u = new User(Alias = 'standt', Email='standardus123123er@testorg.com',
                          EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
                          LocaleSidKey='en_US', ProfileId = p.Id,
                          TimeZoneSidKey='America/Los_Angeles',
                          UserName=uniqueUserName);
        
        insert u ;
        UserController uuu = new UserController();
    
        UserWrapper testWrap=new UserWrapper();
        testWrap.isSelected = true;
        testWrap.UserEmail = u.email ; 
        testWrap.Name =u.Name ; 
        testWrap.userID = u.UserName ; 
        
        List<UserWrapper> dmeo12 =new List<UserWrapper>(); 
        dmeo12.add(testWrap);
        UserController.fetchUser('Testing','Name' ,false);
        UserController.removeUsers(JSON.serialize(dmeo12));
        UserController.getUserName(u.Id);
        UserController.performAction(JSON.serialize(dmeo12), dmeo12);
    }
}

Thanks, let us know if it helps you 
This was selected as the best answer
Harsha ShriHarsha Shri

Hi Piyush & Raj,

I really appriciate your help in this. Thank you very much Piyush. This kind of help is really encouraging developers like us. Thanks once again

I have one doubt here. I want to use system.assert statement in this test class. How to use this. Please suggest how to write system.assert statement in this test class