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
Cloud AtlasCloud Atlas 

Test Coverage for Search Page

Hello Guys,

I have setup a simple SEARCH visualforce page...
I am having a hard time covering test percentage... and am stuck at 35%
Can some one guide me as to how I can improve the code coverage...

I don't think anyone needs VF page as the problem is with test class and the controller. 
 APEX CLASS :
 
public with sharing class URLMonthlySearchController {
	 
    public URL_Monthly_Activity__c usr {get; set;}
     
    public List<URL_Monthly_Activity__c> AllGIDs
    {
        get
        {
            if(con != null)
                return (List<URL_Monthly_Activity__c>)con.getRecords();
            else
                return null ;
        }
        set;
    } 
    
    //Controller
    public URLMonthlySearchController()
    {
        AllGIDs = new List<URL_Monthly_Activity__c>() ;
        usr = new URL_Monthly_Activity__c() ;
    }
    
    //Instantiate the StandardSetController
    public ApexPages.StandardSetController con{get; set;}
    
    public PageReference Search()
    {   
        if(usr.GID__c != null && usr.Month__c != null && usr.Year__c != null)
        {
            con = new ApexPages.StandardSetController(Database.getQueryLocator([SELECT Id ,GID__c, Month__c, Year__c,Total_Article_Creates__c, 
                                                                                Total_Compliant_Article_Creates__c,  Total_Article_Updates__c, 
                                                                                Total_Compliant_Article_Updates__c, Total_Newsletter_Creates__c, 
                                                                                Total_Compliant_Newsletter_Creates__c, GAPageviews__c, URL__c  
                                                                                FROM URL_Monthly_Activity__c 
                                                                                WHERE ( URL_Monthly_Activity__c.GID__c =: usr.GID__c AND URL_Monthly_Activity__c.Month__c =: usr.Month__c AND URL_Monthly_Activity__c.Year__c =: usr.Year__c)]));
 
            // sets the number of records in each page set
            con.setPageSize(50);
        }
        else
        {
            con = null;
        }
        return null ;
    }
    
     public PageReference Cancel()
    { 
        return new PageReference('/home/home.jsp');
    }   
        
    
    //Boolean to check if there are more records after the present displaying records
    public Boolean hasNext
    {
        get
        {
            return con.getHasNext();
        }
        set;
    }
 
    //Boolean to check if there are more records before the present displaying records
    public Boolean hasPrevious
    {
        get
        {
            return con.getHasPrevious();
        }
        set;
    }
 
    //Page number of the current displaying records
    public Integer pageNumber
    {
        get
        {
            return con.getPageNumber();
        }
        set;
    }

    //Returns the previous page of records
    public void previous()
    {
        con.previous();
    }
 
    //Returns the next page of records
    public void next()
    {
        con.next();
    }
}

TEST CLASS :
 
@isTest
public class URLMonthlySearchController_Test {
    
    public static testMethod void testPage(){
        
        PageReference pageRef = Page.URLMonthlySearch;
        Test.setCurrentPage(pageRef);
      
        //ApexPages.StandardSetController pageController = new ApexPages.StandardSetController();
        
        URLMonthlySearchController controller = new URLMonthlySearchController();
        //List<URL_Monthly_Activity__c> urlMon = controller.search();
        
        controller.search();
        
    }
}

Any help is appreciated.
Thanks! ​
Best Answer chosen by Cloud Atlas
v varaprasadv varaprasad
Hi ,

Please follow the below steps to improve your code coverage : 
 
@isTest
public class URLMonthlySearchController_Test {

    @testsetup
    public static void testData(){
        List<URL_Monthly_Activity__c> AllGIDs = new List<URL_Monthly_Activity__c>();	


    
        //Sample test data inserting here:
        for(integer i =0; i<10;i++){
            URL_Monthly_Activity__c urlData = new URL_Monthly_Activity__c(
                urlData.name = 'test'+i;  
                //Add test data with all fields in your class
            );
            AllGIDs.add(urlData);
        
        }
		
		insert AllGIDs;
}		
    
    public static testMethod void testPage(){
        List<URL_Monthly_Activity__c> AllGs = [select id from URL_Monthly_Activity__c ];//Add all fields in this query.
        PageReference pageRef = Page.URLMonthlySearch;
        Test.setCurrentPage(pageRef);
      
        ApexPages.StandardSetController pageController = new ApexPages.StandardSetController(AllGs);
        URLMonthlySearchController  ams = new URLMonthlySearchController();       
        ams.search();
		ams.Cancel();
		ams.previous();
		ams.next();
		integer pgn = ams.pageNumber();
		Boolean bol1 = ams.hasNext();
		Boolean bol2 = ams.hasPrevious();
        
    }
}


Please follow below salesforce Best Practice for Test Classes :-

1. Test class must start with @isTest annotation if class class version is more than 25
2. Test environment support @testVisible , @testSetUp as well
3. Unit test is to test particular piece of code working properly or not .
4. Unit test method takes no argument ,commit no data to database ,send no email ,flagged with testMethod keyword .
5. To deploy to production at-least 75% code coverage is required
6. System.debug statement are not counted as a part of apex code limit.
7. Test method and test classes are not counted as a part of code limit
9. We should not focus on the  percentage of code coverage ,we should make sure that every use case should covered including positive, negative,bulk and single record .
Single Action -To verify that the the single record produces the correct an expected result .
Bulk action -Any apex record trigger ,class or extension must be invoked for 1-200 records .
Positive behavior : Test every expected behavior occurs through every expected permutation , i,e user filled out every correctly data and not go past the limit .
Negative Testcase :-Not to add future date , Not to specify negative amount.
Restricted User :-Test whether a user with restricted access used in your code .
10. Test class should be annotated with @isTest .
11 . @isTest annotation with test method  is equivalent to testMethod keyword .
12. Test method should static and no void return type .
13. Test class and method default access is private ,no matter to add access specifier .
14. classes with @isTest annotation can't be a interface or enum .
15. Test method code can't be invoked by non test request .
16. Stating with salesforce API 28.0 test method can not reside inside non test classes .
17. @Testvisible annotation to make visible private methods inside test classes.
18. Test method can not be used to test web-service call out . Please use call out mock .
19. You can't  send email from test method.
20.User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true) .
21. SeeAllData=true will not work for API 23 version eailer .
22. Accessing static resource test records in test class e,g List<Account> accList=Test.loadData(Account,SobjectType,'ResourceName').
23. Create TestFactory class with @isTest annotation to exclude from organization code size limit .
24. @testSetup to create test records once in a method  and use in every test method in the test class .
25. We can run unit test by using Salesforce Standard UI,Force.com IDE ,Console ,API.
26. Maximum number of test classes run per 24 hour of period is  not grater of 500 or 10 multiplication of test classes of your organization.
27. As apex runs in system mode so the permission and record sharing are not taken into account . So we need to use system.runAs to enforce record sharing .
28. System.runAs will not enforce user permission or field level permission .
29. Every test to runAs count against the total number of DML issued in the process .

Hope it helps you.

Please let me know in case of any other assistance.

Thanks
Varaprasad 




 

All Answers

v varaprasadv varaprasad
Hi ,

Please follow the below steps to improve your code coverage : 
 
@isTest
public class URLMonthlySearchController_Test {

    @testsetup
    public static void testData(){
        List<URL_Monthly_Activity__c> AllGIDs = new List<URL_Monthly_Activity__c>();	


    
        //Sample test data inserting here:
        for(integer i =0; i<10;i++){
            URL_Monthly_Activity__c urlData = new URL_Monthly_Activity__c(
                urlData.name = 'test'+i;  
                //Add test data with all fields in your class
            );
            AllGIDs.add(urlData);
        
        }
		
		insert AllGIDs;
}		
    
    public static testMethod void testPage(){
        List<URL_Monthly_Activity__c> AllGs = [select id from URL_Monthly_Activity__c ];//Add all fields in this query.
        PageReference pageRef = Page.URLMonthlySearch;
        Test.setCurrentPage(pageRef);
      
        ApexPages.StandardSetController pageController = new ApexPages.StandardSetController(AllGs);
        URLMonthlySearchController  ams = new URLMonthlySearchController();       
        ams.search();
		ams.Cancel();
		ams.previous();
		ams.next();
		integer pgn = ams.pageNumber();
		Boolean bol1 = ams.hasNext();
		Boolean bol2 = ams.hasPrevious();
        
    }
}


Please follow below salesforce Best Practice for Test Classes :-

1. Test class must start with @isTest annotation if class class version is more than 25
2. Test environment support @testVisible , @testSetUp as well
3. Unit test is to test particular piece of code working properly or not .
4. Unit test method takes no argument ,commit no data to database ,send no email ,flagged with testMethod keyword .
5. To deploy to production at-least 75% code coverage is required
6. System.debug statement are not counted as a part of apex code limit.
7. Test method and test classes are not counted as a part of code limit
9. We should not focus on the  percentage of code coverage ,we should make sure that every use case should covered including positive, negative,bulk and single record .
Single Action -To verify that the the single record produces the correct an expected result .
Bulk action -Any apex record trigger ,class or extension must be invoked for 1-200 records .
Positive behavior : Test every expected behavior occurs through every expected permutation , i,e user filled out every correctly data and not go past the limit .
Negative Testcase :-Not to add future date , Not to specify negative amount.
Restricted User :-Test whether a user with restricted access used in your code .
10. Test class should be annotated with @isTest .
11 . @isTest annotation with test method  is equivalent to testMethod keyword .
12. Test method should static and no void return type .
13. Test class and method default access is private ,no matter to add access specifier .
14. classes with @isTest annotation can't be a interface or enum .
15. Test method code can't be invoked by non test request .
16. Stating with salesforce API 28.0 test method can not reside inside non test classes .
17. @Testvisible annotation to make visible private methods inside test classes.
18. Test method can not be used to test web-service call out . Please use call out mock .
19. You can't  send email from test method.
20.User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true) .
21. SeeAllData=true will not work for API 23 version eailer .
22. Accessing static resource test records in test class e,g List<Account> accList=Test.loadData(Account,SobjectType,'ResourceName').
23. Create TestFactory class with @isTest annotation to exclude from organization code size limit .
24. @testSetup to create test records once in a method  and use in every test method in the test class .
25. We can run unit test by using Salesforce Standard UI,Force.com IDE ,Console ,API.
26. Maximum number of test classes run per 24 hour of period is  not grater of 500 or 10 multiplication of test classes of your organization.
27. As apex runs in system mode so the permission and record sharing are not taken into account . So we need to use system.runAs to enforce record sharing .
28. System.runAs will not enforce user permission or field level permission .
29. Every test to runAs count against the total number of DML issued in the process .

Hope it helps you.

Please let me know in case of any other assistance.

Thanks
Varaprasad 




 
This was selected as the best answer
Cloud AtlasCloud Atlas
Hey Varaprasad,

Thanks a ton.
Your code helped a lot..
I did had to make few correction in the testPage method for Boolean and Void .
Code coverage is currently at 60%.
public static testMethod void testPage(){
        List<URL_Monthly_Activity__c> AllGs = [SELECT Id, GID__c, Month__c, Year__c, URL__c FROM URL_Monthly_Activity__c WHERE (GID__c =:5 AND Month__c =: currentdate.month() AND Year__c =: currentdate.year())]; 
                                                      
                                               		
        PageReference pageRef = Page.URLMonthlySearch;
        pageRef.getParameters().put('gid', '5');
        Test.setCurrentPage(pageRef);
      
        ApexPages.StandardSetController pageController = new ApexPages.StandardSetController(AllGs);
        URLMonthlySearchController  ams = new URLMonthlySearchController();       
        ams.Search();
		ams.Cancel();
		ams.hasNext = true;
        ams.hasPrevious = false;
        ams.pageNumber = 1;
        ams.previous();
        ams.next();
        //ams.con = ;
        
    }

It just won't cover, the following ... 
But I'll work on it to figure out what might be the problem.

User-added image

Thanks for your assistance.
v varaprasadv varaprasad
@testsetup
    public static void testData(){
        List<URL_Monthly_Activity__c> AllGIDs = new List<URL_Monthly_Activity__c>();	


    
        //Sample test data inserting here:
        for(integer i =0; i<10;i++){
            URL_Monthly_Activity__c urlData = new URL_Monthly_Activity__c(
                urlData.name = 'test'+i;  
                //Add test data with all fields in your class
            );
            AllGIDs.add(urlData);
        
        }
		
		insert AllGIDs;


Insert above tesdata it will cover remaining methods.
Hope it helps you, please mark it as best solution.
Thanks
Varaprasad


 
Cloud AtlasCloud Atlas
Oh. I did that.
I had custom data to insert, which was done that's how I reached 60%.
The code that I posted was only just to show the changes I made to testpage method.
The entire test class is much bigger.
Thanks for your help.