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
sfpsfp 

How can do code coverage apex class constructor method?

Code : 
When ever its adding a new User the Id value null and edit time passing the value query string. 

public UserController() {
        
        id =  apexpages.currentpage().getparameters().get('id');
                
        if (id != null) {
            id = string.escapeSingleQuotes(id);
            user = new User__c();    
            try {                                
                user = [SELECT Id, Id__c, FirstName__c, LastName__c, MobilePhone__c, Username__c, Status__c FROM User__c where id =: id];
                
            } catch(QueryException e) {
                ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, 'Invalid User: '+id);
                ApexPages.addMessage(msg);
            }
        }
    }

Please suggest

Kind Regards,
Mohan
Suraj GharatSuraj Gharat
Before calling the constructor, you need to set "current page" and required parameters. Refer below code:
Test.setCurrentPage(Page.NameOfYourPage);
ApexPages.currentPage().getParameters().put('id',id_of_any_user);
UserController con=new UserController();
For more details, go to this link - https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_controller_error_handling.htm
 
sfpsfp
Hi Suraj,

 Thanks for your help, How will code coverage with catch exception? 

Kind Regards,
Mohan
sfpsfp
Hi Suraj,

Thanks for your help, I have done InValidIdException coverage also. Thanks once again. 

static testMethod void inValidIdException() 
    {
        User__c user = new User__c();
        user.FirstName__c = 'Mohan';
        user.LastName__c = 'p';
        user.Username__c = 'mohan.puttu@test.com';
        user.MobilePhone__c = '079666665';        
        user.Status__c = 'Active';
        user.Id__c = 1234567;
        insert user;
                
        Test.StartTest();
         
        //set mock response from postRemote User Callout
        Test.setMock(HttpCalloutMock.class, new MockpostRemoteUser());
        
         
        PageReference pageRef = Page.UserList; // Add your VF page Name here
        pageRef.getParameters().put('id', String.valueOf('12544252222222'));
        Test.setCurrentPage(pageRef);
        
        UserController userc = new UserController();
        userc.user = user;
        //call saveUser(), should result in creating a User__c record
        userc.saveUser();
        
        //try to get error message 
        ApexPages.Message[] pageMessages = ApexPages.getMessages();
        System.assertNotEquals(0, pageMessages.size());
        
        // Check that the error message you are expecting is in pageMessages
        Boolean messageFound = false;

        for(ApexPages.Message message : pageMessages) {

            system.debug(message.getSummary());
            system.debug(message.getDetail());

            if(message.getSummary().contains('Invalid User:') && message.getSeverity() == ApexPages.Severity.ERROR) {
                messageFound = true;        
            }
        }

        System.assert(messageFound, 'Could not find any page error');
        
        Test.StopTest();
    }        

Kind Regards,
Mohan
Suraj GharatSuraj Gharat
To cover code inside catch block, you need to create a test that runs into an exception, in your case it is "QueryException". For achieve this you may pass an invalid id to the page, like:
ApexPages.currentPage().getParameters().put('id','invalidid');
Then collect this id in "String" type variable, like:
 
String id=ApexPages.currentpage().getparameters().get('id');
And use this id in your above controller, this will result in "QueryException" and catch block will be called.