• subrat panda
  • NEWBIE
  • 10 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 3
    Questions
  • 2
    Replies
@isTest
public with sharing class CP_AccountTabExtTest{

    /*** Instance Variables ***/
    
    /*** Static Variables (Static) ***/
    private static User userCPU;
    private static User userCPM;
    private static List<User> users;
    private static Map<Integer, Account> mapParentAccounts;
    private static Account parentAccount;
    private static Map<Integer, Account> mapChildAccounts;
    private static Map<Integer, Contact> mapContacts;   
    
    /*** Constant Variables (Static Final) ***/
    
    /*** Public Instance Methods ***/   

    /*** Private Instance Methods ***/  
    
    /*** Static Methods ***/        
            
    static void GenerateData()
    {
        Profile objProfile=[Select Id from Profile where Name=: CP_TestDataFactory.profileAdmin];
        UserRole objRole=[select id from UserRole where PortalType='None' limit 1];
        User objUser = new User(alias = 'TestUser', 
                          email='CP_TestDFUser@PhilipsOC.test',
                          emailencodingkey='UTF-8', 
                          lastname='Testing', 
                          languagelocalekey='en_US',
                          localesidkey='en_US', 
                          UserRoleId=objRole.Id, 
                          profileid=objProfile.ID,
                          country='United States',
                          timezonesidkey='America/Los_Angeles', 
                          username='CP_TestDFUser@PhilipsOC.test',
                          isActive = true);
        User thisUser = [ select Id from User where Id = :UserInfo.getUserId()];
        System.runAs(thisUser) {
            insert objUser;
        }
        
        parentAccount = CP_TestDataFactory.GenerateParentAccount(objUser.Id);
        insert parentAccount;

        mapChildAccounts = CP_TestDataFactory.GenerateChildAccounts(250, parentAccount.Id);
        insert mapChildAccounts.values();
        
        mapContacts = CP_TestDataFactory.GenerateContacts(20, parentAccount.Id);
        insert mapContacts.values();
        
        Profile profileCPU = [select id from profile where name=: CP_TestDataFactory.profileCPU ];        
        userCPU = new User(alias = 'TestCPU', 
                          email='CP_TestDFUserCPU@PhilipsOC.test',
                          emailencodingkey='UTF-8', 
                          lastname='Testing', 
                          languagelocalekey='en_US',
                          localesidkey='en_US', 
                          profileid=profileCPU.ID,
                          contactId = mapContacts.get(1).Id,
                          country='United States',
                          timezonesidkey='America/Los_Angeles', 
                          username='CP_TestDFUserCPU@PhilipsOC.test',
                          isActive = true);     
        insert userCPU;     
        
        Profile profileCPM = [select id from profile where name=: CP_TestDataFactory.profileCPM ];        
        userCPM = new User(alias = 'TestCPM', 
                          email='CP_TestDFUserCPM@PhilipsOC.test',
                          emailencodingkey='UTF-8', 
                          lastname='Testing', 
                          languagelocalekey='en_US',
                          localesidkey='en_US', 
                          profileid=profileCPM.ID,
                          contactId = mapContacts.get(2).Id,
                          country='United States',
                          timezonesidkey='America/Los_Angeles', 
                          username='CP_TestDFUserCPM@PhilipsOC.test',
                          isActive = true);                 
        insert userCPM;         
        
        users = new List<User>();
        users.add(userCPU);
        users.add(userCPM);
    }
    static testMethod void testAll() {
           GenerateData();
           system.runAs(userCPU){
            PageReference pageref = Page.CP_AccountTab;
            Test.setCurrentPage(pageRef);
            ApexPages.StandardController controller = new ApexPages.StandardController(parentAccount);
            CP_AccountTabExt acExtController = new CP_AccountTabExt();
            String q = 'SELECT Name FROM ACCOUNT LIMIT 1';
            ApexPages.StandardSetController ACC = new ApexPages.StandardSetController(Database.getQueryLocator(q));
            List<SelectOption> ListViews = ACC.getListViewOptions();
            System.assertEquals(ListViews , acExtController.getAccountExistingViews());
            List<Account> accounts = [Select Id, Name, AccountNumber, ShippingStreet, ShippingCity, ShippingState, 
                                     ShippingCountry FROM Account ORDER BY Name ASC LIMIT 10000];
            System.assertEquals(accounts , acExtController.getAccounts());
            PageReference expectedPage = Page.CP_AccountDetail;
            String nextPage = acExtController.AccountDetailPage;
            System.assertEquals(expectedPage.getUrl(), nextPage); 
            acExtController.resetFilter();
            acExtController.prev();
            acExtController.next();
            acExtController.lastPage();
            acExtController.firstPage();
            
        }
		   system.runAs(userCPM){
            PageReference pageref = Page.CP_AccountTab;
            Test.setCurrentPage(pageRef);
            ApexPages.StandardController controller = new ApexPages.StandardController(parentAccount);
            CP_AccountTabExt acExtController = new CP_AccountTabExt();
            String q = 'SELECT Name FROM ACCOUNT LIMIT 1';
            ApexPages.StandardSetController ACC = new ApexPages.StandardSetController(Database.getQueryLocator(q));
            List<SelectOption> ListViews = ACC.getListViewOptions();
            System.assertEquals(ListViews , acExtController.getAccountExistingViews());
            List<Account> accounts = [Select Id, Name, AccountNumber, ShippingStreet, ShippingCity, ShippingState, 
                                     ShippingCountry FROM Account ORDER BY Name ASC LIMIT 10000];
            System.assertEquals(accounts , acExtController.getAccounts());
            PageReference expectedPage = Page.CP_AccountDetail;
            String nextPage = acExtController.AccountDetailPage;
            System.assertEquals(expectedPage.getUrl(), nextPage); 
            acExtController.resetFilter();
            acExtController.prev();
            acExtController.next();
            acExtController.lastPage();
            acExtController.firstPage();
            
        }	
    }
	static testMethod void testNext()}{
		GenerateData();
		system.runAs(userCPU){
            PageReference pageref = Page.CP_AccountTab;
            Test.setCurrentPage(pageRef);
            ApexPages.StandardController controller = new ApexPages.StandardController(parentAccount);
            CP_AccountTabExt acExtController = new CP_AccountTabExt();
		}
		system.runAs(userCPM){
            PageReference pageref = Page.CP_AccountTab;
            Test.setCurrentPage(pageRef);
            ApexPages.StandardController controller = new ApexPages.StandardController(parentAccount);
            CP_AccountTabExt acExtController = new CP_AccountTabExt();
		}
	
	}
	static testMethod void testPrev(){
		GenerateData();
		system.runAs(userCPU){
            PageReference pageref = Page.CP_AccountTab;
            Test.setCurrentPage(pageRef);
            ApexPages.StandardController controller = new ApexPages.StandardController(parentAccount);
            CP_AccountTabExt acExtController = new CP_AccountTabExt();
		}
		system.runAs(userCPM){
            PageReference pageref = Page.CP_AccountTab;
            Test.setCurrentPage(pageRef);
            ApexPages.StandardController controller = new ApexPages.StandardController(parentAccount);
            CP_AccountTabExt acExtController = new CP_AccountTabExt();
		}	
	
	}
    static testMethod void testLast(){
		GenerateData();
		system.runAs(userCPU){
            PageReference pageref = Page.CP_AccountTab;
            Test.setCurrentPage(pageRef);
            ApexPages.StandardController controller = new ApexPages.StandardController(parentAccount);
            CP_AccountTabExt acExtController = new CP_AccountTabExt();
		}
		system.runAs(userCPM){
            PageReference pageref = Page.CP_AccountTab;
            Test.setCurrentPage(pageRef);
            ApexPages.StandardController controller = new ApexPages.StandardController(parentAccount);
            CP_AccountTabExt acExtController = new CP_AccountTabExt();
		}
	
	}
	static testMethod void testFirst(){
		GenerateData();
		system.runAs(userCPU){
            PageReference pageref = Page.CP_AccountTab;
            Test.setCurrentPage(pageRef);
            ApexPages.StandardController controller = new ApexPages.StandardController(parentAccount);
            CP_AccountTabExt acExtController = new CP_AccountTabExt();
		}
		system.runAs(userCPM){
            PageReference pageref = Page.CP_AccountTab;
            Test.setCurrentPage(pageRef);
            ApexPages.StandardController controller = new ApexPages.StandardController(parentAccount);
            CP_AccountTabExt acExtController = new CP_AccountTabExt();
		}
	}
    }



public with sharing class CP_AccountTabExt {

  /*** Instance Variables ***/

  public String AccountFilterId { get; set;}
  private String query = 'Select Id, Name, AccountNumber, ShippingStreet, ShippingCity, ShippingState, ShippingCountry FROM Account ORDER BY Name ASC LIMIT 10000';    
    private Integer pageSize = 50;
  
    /*** Static Variables (Static) ***/
    
    /*** Constant Variables (Static Final) ***/    
      
    /*** Public Instance Methods ***/
  public CP_AccountTabExt(){}
  
  public String AccountDetailPage {
    get{
            if(AccountDetailPage == null){
        PageReference accountDetail = Page.CP_AccountDetail;
                return accountDetail.getURL();
      }
      return '';
    }
    Set;
  }  

  public ApexPages.StandardSetController AccountSetController {
        get{
            if(AccountSetController == null){
                AccountSetController = new ApexPages.StandardSetController(Database.getQueryLocator(query));
                AccountSetController.setPageSize(pageSize);

                // We have to set FilterId after Pagesize, else it will not work
                if(AccountFilterId != null)
                {
                  AccountSetController.setFilterId(AccountFilterId);
                }
            }
            return AccountSetController;
        }set;
    }

  public CP_AccountTabExt(ApexPages.StandardSetController ssc) {  }

    //Navigate to first Page
    public void firstPage()
    {
      AccountSetController.first();
    }

    //Navigate to last Page
    public void lastPage()
    {
      AccountSetController.last();
    }

    //Navigate to Next page
    public void next()
    {
      if(AccountSetController.getHasNext())
      {
        AccountSetController.next();
      }
    }

    //Navigate to Prev Page
    public void prev()
    {
      if(AccountSetController.getHasPrevious())
      {
        AccountSetController.previous();
      }
    }

    public List<Account> getAccounts()
    {
      return (List<Account>)AccountSetController.getRecords();
    }

    //Get all available list view for Account
    public SelectOption[] getAccountExistingViews(){
        return AccountSetController.getListViewOptions();
    }

    /**
    * Reset List View
    */
    public PageReference resetFilter()
    {
      AccountSetController = null;
        AccountSetController.setPageNumber(1);
        return null;
    }
   
    
}

This will be a big help as I am new to salesforce test class.
Controller class

Public without sharing class CP_AccountTabController {

/*** Instance Variables ***/

    public List<Account> accounts                 {get;set;}    
    public List<Integer> paginationList           {get;set;}
    public Double lastPage                        {get;set;}
    public Integer pageNum                        {get;set;}
    public Integer totalNoOfAccounts              {get;set;}
    public Integer fromAccountCount               {get;set;}
    public Integer toAccountCount                 {get;set;}
    public String selectedSortByFilter            {get;set;}
    public String selectedView                    {get;set;}
    public Final Integer PAGE_SIZE = 50;
      
  private User myUser;
  private Id myAccountId;
    
    /*** Public Instance Methods ***/
    public CP_AccountTabController(){
    myUser = [SELECT Id, Contact.AccountId from User where Id =: UserInfo.getUserId()];
    myAccountId = myUser.Contact.AccountId;
    
        pageNum = ApexPages.currentPage().getParameters().get('pnum')!=null?Integer.valueOf(ApexPages.currentPage().getParameters().get('pnum')):1;
        selectedView  =  ApexPages.currentPage().getParameters().get('selectedView')!=null?ApexPages.currentPage().getParameters().get('selectedView'):'Accounts';
        selectedSortByFilter =  ApexPages.currentPage().getParameters().get('selectedSortByFilter')!=null?ApexPages.currentPage().getParameters().get('selectedSortByFilter'):' AccountNumber desc ';
        accounts = accountList();
    }
   
   /*** Public Instance Methods ***/
    Public PageReference sortCaseList () {
    pageNum = ApexPages.currentPage().getParameters().get('pnum')!=null?Integer.valueOf(ApexPages.currentPage().getParameters().get('pnum')):1;
        selectedSortByFilter =  ApexPages.currentPage().getParameters().get('selectedSortByFilter')!=null?ApexPages.currentPage().getParameters().get('selectedSortByFilter'):' AccountNumber desc ';
        accounts = accountList();
        return null;
    }
    
    /*** Public Instance Methods ***/
    public pageReference resetFilter(){
    pageNum = 1;
        accounts = accountList();
        return null;
    }
    
    /*** Public Instance Methods ***/
    public List<SelectOption> getView() {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('Accounts','Accounts'));
        options.add(new SelectOption('Bad_Credit_Accounts','Bad Credit Accounts'));
        options.add(new SelectOption('By_TimeZone','By TimeZone'));
        options.add(new SelectOption('New_This_Week','New This Week'));
        options.add(new SelectOption('Recently_Viewed_Accounts','Recently Viewed Accounts'));
        return options;
    }
   
    /*** Public Instance Methods ***/
    public List<Account> accountList() {
        List<account> accList = new List<Account>();
        if(myAccountId == null){
            return accList;
        }    
        String accountQuery = '';
        string strIntialQuery = '';
        if(selectedView == 'Accounts'){
          strIntialQuery = 'SELECT Id, Customer_Portal_Parent_Account__c FROM Account WHERE Customer_Portal_Parent_Account__c =: myAccountId ORDER BY ' + selectedSortByFilter + ' limit 999950';
        }
    else {
            String filterStr = viewFilter(selectedView);
            strIntialQuery = 'select id from Account WHERE' + ' Customer_Portal_Parent_Account__c =: myAccountId AND' +filterStr+' ORDER BY ' + selectedSortByFilter + ' limit 999950';
        }
        transient List<Account> accountList = database.query(strIntialQuery ); //Pick all Accounts. Maximum limit is 1 million. We pick only ids. So query will be fast.
        totalNoOfAccounts =  accountList.size();
    
        if(totalNoOfAccounts < 1){
            return accList;
        }    
    
        set<String> accountSetIds = new set<string>();
        if(pageNum == 1 && totalNoOfAccounts > PAGE_SIZE) {//For first page
            For(integer i= 0; i < PAGE_SIZE; i++){
                accountSetIds.add(accountList[i].id);
            }
        }else if(totalNoOfAccounts < PAGE_SIZE && pageNum == 1){
            For(integer i= 0; i < totalNoOfAccounts; i++){
                accountSetIds.add(accountList[i].id);
            }
        }
        else if(pageNum*PAGE_SIZE <  totalNoOfAccounts) { //If the records that will be used in for loop are less than total records
            For(integer i= (((pageNum-1)*PAGE_SIZE)); i< pageNum*PAGE_SIZE ; i++){
                accountSetIds.add(accountList[i].id);
            }
        }
        else {//This works for Last set of data
            For(integer i= (pageNum-1)*PAGE_SIZE; i< totalNoOfAccounts; i++){
                accountSetIds.add(accountList[i].id);
            }
        }
        List<String> accountListIds = New List<String>();
        if(accountSetIds.size() > 0){
            accountListIds.addAll(accountSetIds);
        }
        
        
        // Generate Pagination
        lastpage = Integer.valueOf(Math.ceil(Decimal.ValueOf(totalNoOfAccounts)/Decimal.ValueOf(PAGE_SIZE)));
        paginationList = getPaginationList(pageNum, totalNoOfAccounts , PAGE_SIZE);
        if(lastpage != 0){
            toAccountCount = Pagenum * PAGE_SIZE;
            fromAccountCount = toAccountCount-(PAGE_SIZE - 1);
        }
       
        if(pageNum == 1 || pageNum < 1){
            if(lastpage != 0){
                fromAccountCount = 1;
                toAccountCount = PAGE_SIZE;
                pageNum = 1;
            }
            else{
                fromAccountCount = 0;
                toAccountCount = 0;
                pageNum = 1;
            }
        }
        if(pageNum == Integer.ValueOf(lastpage) || (pageNum > Integer.ValueOf(lastpage) && lastpage != 0)){
            fromAccountCount = (Integer.ValueOf(lastpage) - 1) * PAGE_SIZE + 1;
            toAccountCount = totalNoOfAccounts;
            pageNum = Integer.ValueOf(lastpage);
        }
        
        CP_List_View_CS__c objListViewCS = CP_List_View_CS__c.getValues('Account');
        String strFields = objListViewCS.Fields__c;
        
        String accountIdString = '';
        if(accountListIds.size() > 0){
            accountIdString = quoteKeySet(accountListIds);
        }
        
        if(selectedView == 'Accounts'){
      accountQuery = 'select '+ strFields +' from Account WHERE Customer_Portal_Parent_Account__c =: myAccountId ';
      if (accountIdString != '') {
              accountQuery += 'AND Id in '+accountIdString;
      }
      accountQuery += ' ORDER BY '+selectedSortByFilter;
        }
    else {
            String filterStr = viewFilter(selectedView);
            accountQuery = 'select '+ strFields +' from Account where' + ' Customer_Portal_Parent_Account__c =: myAccountId AND' + filterStr;
      if (accountIdString != '') {
        accountQuery += 'AND Id in '+accountIdString;
      }
      accountQuery += ' ORDER BY '+selectedSortByFilter;      
        }
        accList = Database.Query(accountQuery);
        return accList;
               
    }

    Public string viewFilter(String filterValue){
        String filterStr = '';
        if(filterValue == 'Bad_Credit_Accounts'){
            filterStr  = ' Credit_Status__c !=null and Sales_Block__c !=null ';
        }else if(filterValue == 'By_TimeZone'){
            filterStr  = ' Time_Zone__c != null ';
        }else if(filterValue == 'New_This_Week'){
            filterStr  = ' createddate = THIS_WEEK ' ;
        }else if(filterValue == 'Recently_Viewed_Accounts'){
            filterStr  = ' LastViewedDate != null '; 
        }
        return filterStr ;
    }
    
    public String quoteKeySet(List<String> mapKeySet) {
        String newSetStr = '' ;
        for(String str : mapKeySet)
            newSetStr += '\'' + str + '\',';
        
        newSetStr = newSetStr.lastIndexOf(',') > 0 ? '(' + newSetStr.substring(0,newSetStr.lastIndexOf(',')) + ')' : newSetStr ;
        return newSetStr;
        
    } 
   
    Public  List<Integer> getPaginationList (Integer curPageNo, Integer totalResults, Integer pagesize) {
        List<Integer> paginationList = new List<Integer>(); 
        Double totalNumOfPages = math.ceil(Double.valueof(totalResults)/Double.valueof(pagesize));
        Integer index;
        If(curPageNo <= 4 ){
            for (index=curPageNo-3;index<curPageNo;index+=1) {//Enter Here for first 3 pages
                if(index<=0) {
                    continue;  
                }
                paginationList.add(index);
            }
            paginationList.add(curPageNo);
            Integer jindex;      
            for (jindex=curPageNo+1;jindex<=7;jindex+=1) {
                If(jindex >= totalNumOfPages+1){
                    break;
                }
                paginationList.add(jindex);
            }
        }else If(curPageNo >= 4 && curPageNo < totalNumOfPages-3){//Enter here for Pages In Between
                for (index=curPageNo-3;index<curPageNo;index+=1) {
                    if(index<=0) {
                        continue;  
                    }
                    paginationList.add(index);
                }
                paginationList.add(curPageNo);
                Integer jindex;      
                for (jindex=curPageNo+1;jindex<=curPageNo+3;jindex+=1) {
                    if(jindex > totalResults/pageSize){
                        break;
                    }
                    paginationList.add(jindex);
                }
        } else {//Enter Here for last 3 pages
                Integer tempNum;//Number of digits before last three digits to keep the list count(7) for last three digits
                if(curPageNo == totalNumOfPages-3){tempNum = 3;}
                If(curPageNo == totalNumOfPages-2){tempNum = 4;}
                If(curPageNo == totalNumOfPages-1){tempNum = 5;}
                If(curPageNo == totalNumOfPages)  {tempNum = 6;}
                for (index=curPageNo-tempNum;index<curPageNo;index+=1) {
                    if(index<=0) {
                        continue;  
                    }
                    paginationList.add(index);
                }
                paginationList.add(curPageNo);
                Integer jindex;      
                for (jindex=curPageNo+1;jindex<=totalNumOfPages+2;jindex+=1) {
                    if(jindex > totalNumOfPages){
                    break;
                    }
                    paginationList.add(jindex);
                }
        }
        return paginationList;
    }
}

Class for creating test data
@isTest
public with sharing class CP_TestDataFactory {

    /*** Instance Variables ***/
    
    /*** Static Variables (Static) ***/
    
    /*** Constant Variables (Static Final) ***/
    public final static String profileCPM = 'CP_CustomerPortalManager_PR';  
    public final static String profileCPU = 'CP_CustomerPortalUser_PR'; 
    public final static String profileAdmin = 'System Administrator'; 
    public final static String typeCustomerPortalParent = 'Customer Portal Parent'; 
    public final static String roleCustomerPortalUser = 'Customer Portal User'; 
    
    /*** Public Instance Methods ***/

    /*** Private Instance Methods ***/  
    
    /*** Static Methods ***/        
   
    //Generates a list of ParentAccounts
    public static Map<Integer, Account> GenerateParentAccounts(Integer count, Id ownerId){
        Map<Integer, Account> result = new Map<Integer, Account>();
        for(Integer i = 0; i < count; i++) {
            result.put(i, new Account(Name = 'CP_TestDFAccount_' + i,
                        Type = typeCustomerPortalParent,
                        ownerId = ownerId,
                        Credit_status__c = 'Good',
                        ShippingStreet = 'TestStreet',
                        ShippingCity = 'Chicago',
                        ShippingState = 'IL',
                        ShippingPostalCode = '60606',               
                        ShippingCountry = 'US',
                        sales_org__c = 'CA93')
                      );
        }
        return result;
    }       
    
    //Generates a single ParentAccount
    public static Account GenerateParentAccount(Id ownerId){
        Account result = new Account(Name = 'CP_TestDFAccount_',
                        Type = typeCustomerPortalParent,
                        ownerId = ownerId,
                        Credit_status__c = 'Good',
                        ShippingStreet = 'TestStreet',
                        ShippingCity = 'Chicago',
                        ShippingState = 'IL',
                        ShippingPostalCode = '60606',               
                        ShippingCountry = 'US',
                        sales_org__c = 'CA93');
        return result;
    }       
    
    //Generates a list of ChildAccounts
    public static Map<Integer, Account> GenerateChildAccounts(Integer count, Id parentId){
        Map<Integer, Account> result = new Map<Integer, Account>();
        for(Integer i = 0; i < count; i++) {
            result.put(i, new Account(Name = 'CP_TestDFAccount_' + i,
                        Customer_Portal_Parent_Account__c = parentId,
                        Credit_status__c = 'Good',
                        ShippingStreet = 'TestStreet',
                        ShippingCity = 'Chicago',
                        ShippingState = 'IL',
                        ShippingPostalCode = '60606',               
                        ShippingCountry = 'US',
                        sales_org__c = 'CA93')
                      );
        }
        return result;
    }           

    //Generates a list of Contacts given a shared AccountId
    public static Map<Integer, Contact> GenerateContacts(Integer count, Id accountId){
        Map<Integer, Contact> result = new Map<Integer, Contact>();
        for(Integer i = 0; i < count; i++) {
            result.put(i, new Contact(FirstName = 'CP_TestDFContact_' + i, 
                        LastName = 'Contact',
                        MailingStreet = 'Test Street',
                        Contact_Role__c = roleCustomerPortalUser,
                        AccountID = accountId, 
                        Phone = '1234567890')
                      );
        }
        return result;
    }
  
    //Generates a list of Contacts given a shared AccountId
    public static Map<Integer, Contact> GenerateNonPortalContacts(Integer count, Id accountId){
        Map<Integer, Contact> result = new Map<Integer, Contact>();
        for(Integer i = 0; i < count; i++) {
            result.put(i, new Contact(FirstName = 'CP_TestDFNPContact_' + i, 
                        LastName = 'NPContact',
                        MailingStreet = 'Test Street',
                        AccountID = accountId, 
                        Phone = '1234567890')
                      );
        }
        return result;
    }  

    //Generates a list of Products
    public static Map<Integer, Product2> GenerateProducts(Integer count){
        Map<Integer, Product2> result = new Map<Integer, Product2>();
        for(Integer i = 0; i < count; i++) {
            result.put(i, new Product2(Name = 'CP_TestProduct_' + i));
        }
        return result;
    }    
  
  //Generates a list of Cases with specified count per Account/Contact pair
    public static Map<Integer, Case> GenerateCases(String status, Integer count, Account acct, Contact ct){
        Map<Integer, Case> result = new Map<Integer, Case>();
        for(Integer i = 0; i < count; i++) {
            result.put(i, new Case(Status = status, 
            AccountId = acct.Id,
            ContactId = ct.Id,
        Priority = '3-System Restricted',
            Subject = 'Test Subject ' + i,
            Description = 'Test Description ' + i,
            Customer_Functional_Location__c = 'US',
            Customer_Asset_Number__c = '123' + i,
            Customer_Serial_Number__c = '1' + i,
            Customer_Technical_ID__c = 'Id123' + i)
      );
        }    
        return result;
    }      
  
  //Generates a list of Cases
    public static Map<Integer, Case> GenerateCases(String status, Map<Integer, Account> accounts, Map<Integer, Contact> contacts){
        Map<Integer, Case> result = new Map<Integer, Case>();
        for(Integer i = 0; i < contacts.size(); i++) {
            result.put(i, new Case(Status = status, 
            AccountId = accounts.get(i).Id,
            ContactId = contacts.get(i).Id,
        Priority = '3-System Restricted',
            Subject = 'Test Subject ' + i,
            Description = 'Test Description ' + i,
            Customer_Product__c = 'Test Customer_Product__c',
            Customer_Asset_Number__c = 'Test Asset',
            Customer_Serial_Number__c = 'Test S No',
            Customer_Technical_ID__c = 'Test Tech Id')
      );
        }
        return result;
    }    
  
    //This method is used to generate Random String of supplied length
    public static String constructTestString(Integer length) {
        Blob blobKey = crypto.generateAesKey(128);
        String key = EncodingUtil.convertToHex(blobKey);
        return key.substring(0,length);
    }

Test class

@isTest
private class CP_EnableUserControllerExtTest{
    
    
    /*** Instance Variables ***/
    
    /*** Static Variables (Static) ***/
    private static User userCPU;
    private static Profile cpProfile;
    private static User userCPM;
    private static List<User> users;
    private static Map<Integer, Account> mapParentAccounts;
    private static Account parentAccount;
    private static Map<Integer, Account> mapChildAccounts;
    private static Map<Integer, Contact> mapContacts;   
    
    /*** Constant Variables (Static Final) ***/
    
    /*** Public Instance Methods ***/   

    /*** Private Instance Methods ***/  
    
    /*** Static Methods ***/        
            
    static void GenerateData()
    {
        Profile objProfile=[Select Id from Profile where Name=: CP_TestDataFactory.profileAdmin];
        UserRole objRole=[select id from UserRole where PortalType='None' limit 1];
        User objUser = new User(alias = 'TestUser', 
                          email='CP_TestDFUser@PhilipsOC.test',
                          emailencodingkey='UTF-8', 
                          lastname='Testing', 
                          languagelocalekey='en_US',
                          localesidkey='en_US', 
                          UserRoleId=objRole.Id, 
                          profileid=objProfile.ID,
                          country='United States',
                          timezonesidkey='America/Los_Angeles', 
                          username='CP_TestDFUser@PhilipsOC.test',
                          isActive = true);
        User thisUser = [ select Id from User where Id = :UserInfo.getUserId()];
        System.runAs(thisUser) {
            insert objUser;
        }
        
        parentAccount = CP_TestDataFactory.GenerateParentAccount(objUser.Id);
        insert parentAccount;

        mapChildAccounts = CP_TestDataFactory.GenerateChildAccounts(20, parentAccount.Id);
        insert mapChildAccounts.values();
        
        mapContacts = CP_TestDataFactory.GenerateContacts(20, parentAccount.Id);
        insert mapContacts.values();
        
        Profile profileCPU = [select id from profile where name=: CP_TestDataFactory.profileCPU ];        
        userCPU = new User(alias = 'TestCPU', 
                          email='CP_TestDFUserCPU@PhilipsOC.test',
                          emailencodingkey='UTF-8', 
                          lastname='Testing', 
                          languagelocalekey='en_US',
                          localesidkey='en_US', 
                          profileid=profileCPU.ID,
                          contactId = mapContacts.get(1).Id,
                          country='United States',
                          timezonesidkey='America/Los_Angeles', 
                          username='CP_TestDFUserCPU@PhilipsOC.test',
                          isActive = true);     
        insert userCPU;     
        
        Profile profileCPM = [select id from profile where name=: CP_TestDataFactory.profileCPM ];        
        userCPM = new User(alias = 'TestCPM', 
                          email='CP_TestDFUserCPM@PhilipsOC.test',
                          emailencodingkey='UTF-8', 
                          lastname='Testing', 
                          languagelocalekey='en_US',
                          localesidkey='en_US', 
                          profileid=profileCPM.ID,
                          contactId = mapContacts.get(2).Id,
                          country='United States',
                          timezonesidkey='America/Los_Angeles', 
                          username='CP_TestDFUserCPM@PhilipsOC.test',
                          isActive = true);                 
        insert userCPM;         
        
        users = new List<User>();
        users.add(userCPU);
        users.add(userCPM);
    }
 
    //Test Method
    static testmethod void testConstructor()
    {
        //@Mahak - this test fails
        GenerateData();
        Test.startTest();
        cpProfile = [select id from profile where name=: CP_TestDataFactory.profileCPU ];
        PageReference pageRef = Page.CP_EnableUser;
        Test.setCurrentPage(pageRef);
        System.currentPageReference().getParameters().put('contact', mapContacts.get(3).id);
        ApexPages.currentPage().getParameters().put('retURL', mapContacts.get(3).id);
        System.runAs(userCPM) {
            ApexPages.StandardController controller = new ApexPages.StandardController(new User()); 
            CP_EnableUserControllerExt enableUserCls= New CP_EnableUserControllerExt(controller);
            enableUserCls.setFirstNameCon('Test First Name');
            enableUserCls.setLastNameCon('Test Last Name');
            enableUserCls.setAlias('Alias');
            enableUserCls.setEmail('u2@testorg.com');
            enableUserCls.setUsername('u2@testorg.com');
            enableUserCls.setCommunityNickname('Test Nick Name');
            enableUserCls.selectedPrflId = cpProfile.Id;
            enableUserCls.Alias = 'alias';
            enableUserCls.Email = 'mahak.puri@capgemini.com';
            
            String firstName = enableUserCls.getFirstNameCon();
            String lastName = enableUserCls.getLastNameCon();
            System.assertEquals('Test First Name', enableUserCls.getFirstNameCon());
            System.assertEquals('Test Last Name', enableUserCls.getLastNameCon());
        }
        Test.stopTest();        
    }

    static testmethod void testSaveRecord(){
        GenerateData();
        Test.startTest();
        cpProfile = [select id from profile where name=: CP_TestDataFactory.profileCPU ];
        PageReference pageRef = Page.CP_EnableUser;
        Test.setCurrentPage(pageRef);
        System.currentPageReference().getParameters().put('contact', mapContacts.get(3).id);
        ApexPages.currentPage().getParameters().put('retURL', mapContacts.get(3).id);
        System.runAs(userCPM) {
            ApexPages.StandardController controller = new ApexPages.StandardController(new User()); 
            CP_EnableUserControllerExt enableUserCls= New CP_EnableUserControllerExt(controller);
            enableUserCls.setFirstNameCon('Test First Name');
            enableUserCls.setLastNameCon('Test Last Name');
            enableUserCls.setAlias('Alias');
            enableUserCls.setEmail('u2@testorg.com');
            enableUserCls.setUsername('u2@testorg.com');
            enableUserCls.setCommunityNickname('Test Nick Name');
            enableUserCls.selectedPrflId = cpProfile.Id;
            enableUserCls.Alias = 'alias';
            enableUserCls.Email = 'mahak.puri@capgemini.com';
            PageReference expectedPage = Page.CP_ContactDetail;
            expectedPage.getParameters().put('Id', mapContacts.get(3).id);
            expectedPage.getParameters().put('Cloned', 'false');
            PageReference nextPage = enableUserCls.saveUser();
            System.assertEquals(expectedPage.getUrl(), nextPage.getUrl());
        }
        Test.stopTest();        
    }

    static testmethod void testCancelRecord(){
        GenerateData();
        Test.startTest();
        PageReference pageRef = Page.CP_EnableUser;
        Test.setCurrentPage(pageRef);
        System.currentPageReference().getParameters().put('contact', mapContacts.get(3).id);
        ApexPages.currentPage().getParameters().put('retURL', mapContacts.get(3).id);
        System.runAs(userCPM) {
            ApexPages.StandardController controller = new ApexPages.StandardController(new User()); 
            CP_EnableUserControllerExt enableUserCls= New CP_EnableUserControllerExt(controller);
            PageReference expectedPage = Page.CP_ContactDetail;
            expectedPage.getParameters().put('Id', mapContacts.get(3).id);
            expectedPage.getParameters().put('Cloned', 'false');
            PageReference nextPage = enableUserCls.cancelUser();
            System.assertEquals(expectedPage.getUrl(), nextPage.getUrl());
        }
        Test.stopTest();        
    }
}
Hi I want to know about the schedule apex ? How to write the schedule apex classes?
@isTest
public with sharing class CP_AccountTabExtTest{

    /*** Instance Variables ***/
    
    /*** Static Variables (Static) ***/
    private static User userCPU;
    private static User userCPM;
    private static List<User> users;
    private static Map<Integer, Account> mapParentAccounts;
    private static Account parentAccount;
    private static Map<Integer, Account> mapChildAccounts;
    private static Map<Integer, Contact> mapContacts;   
    
    /*** Constant Variables (Static Final) ***/
    
    /*** Public Instance Methods ***/   

    /*** Private Instance Methods ***/  
    
    /*** Static Methods ***/        
            
    static void GenerateData()
    {
        Profile objProfile=[Select Id from Profile where Name=: CP_TestDataFactory.profileAdmin];
        UserRole objRole=[select id from UserRole where PortalType='None' limit 1];
        User objUser = new User(alias = 'TestUser', 
                          email='CP_TestDFUser@PhilipsOC.test',
                          emailencodingkey='UTF-8', 
                          lastname='Testing', 
                          languagelocalekey='en_US',
                          localesidkey='en_US', 
                          UserRoleId=objRole.Id, 
                          profileid=objProfile.ID,
                          country='United States',
                          timezonesidkey='America/Los_Angeles', 
                          username='CP_TestDFUser@PhilipsOC.test',
                          isActive = true);
        User thisUser = [ select Id from User where Id = :UserInfo.getUserId()];
        System.runAs(thisUser) {
            insert objUser;
        }
        
        parentAccount = CP_TestDataFactory.GenerateParentAccount(objUser.Id);
        insert parentAccount;

        mapChildAccounts = CP_TestDataFactory.GenerateChildAccounts(250, parentAccount.Id);
        insert mapChildAccounts.values();
        
        mapContacts = CP_TestDataFactory.GenerateContacts(20, parentAccount.Id);
        insert mapContacts.values();
        
        Profile profileCPU = [select id from profile where name=: CP_TestDataFactory.profileCPU ];        
        userCPU = new User(alias = 'TestCPU', 
                          email='CP_TestDFUserCPU@PhilipsOC.test',
                          emailencodingkey='UTF-8', 
                          lastname='Testing', 
                          languagelocalekey='en_US',
                          localesidkey='en_US', 
                          profileid=profileCPU.ID,
                          contactId = mapContacts.get(1).Id,
                          country='United States',
                          timezonesidkey='America/Los_Angeles', 
                          username='CP_TestDFUserCPU@PhilipsOC.test',
                          isActive = true);     
        insert userCPU;     
        
        Profile profileCPM = [select id from profile where name=: CP_TestDataFactory.profileCPM ];        
        userCPM = new User(alias = 'TestCPM', 
                          email='CP_TestDFUserCPM@PhilipsOC.test',
                          emailencodingkey='UTF-8', 
                          lastname='Testing', 
                          languagelocalekey='en_US',
                          localesidkey='en_US', 
                          profileid=profileCPM.ID,
                          contactId = mapContacts.get(2).Id,
                          country='United States',
                          timezonesidkey='America/Los_Angeles', 
                          username='CP_TestDFUserCPM@PhilipsOC.test',
                          isActive = true);                 
        insert userCPM;         
        
        users = new List<User>();
        users.add(userCPU);
        users.add(userCPM);
    }
    static testMethod void testAll() {
           GenerateData();
           system.runAs(userCPU){
            PageReference pageref = Page.CP_AccountTab;
            Test.setCurrentPage(pageRef);
            ApexPages.StandardController controller = new ApexPages.StandardController(parentAccount);
            CP_AccountTabExt acExtController = new CP_AccountTabExt();
            String q = 'SELECT Name FROM ACCOUNT LIMIT 1';
            ApexPages.StandardSetController ACC = new ApexPages.StandardSetController(Database.getQueryLocator(q));
            List<SelectOption> ListViews = ACC.getListViewOptions();
            System.assertEquals(ListViews , acExtController.getAccountExistingViews());
            List<Account> accounts = [Select Id, Name, AccountNumber, ShippingStreet, ShippingCity, ShippingState, 
                                     ShippingCountry FROM Account ORDER BY Name ASC LIMIT 10000];
            System.assertEquals(accounts , acExtController.getAccounts());
            PageReference expectedPage = Page.CP_AccountDetail;
            String nextPage = acExtController.AccountDetailPage;
            System.assertEquals(expectedPage.getUrl(), nextPage); 
            acExtController.resetFilter();
            acExtController.prev();
            acExtController.next();
            acExtController.lastPage();
            acExtController.firstPage();
            
        }
		   system.runAs(userCPM){
            PageReference pageref = Page.CP_AccountTab;
            Test.setCurrentPage(pageRef);
            ApexPages.StandardController controller = new ApexPages.StandardController(parentAccount);
            CP_AccountTabExt acExtController = new CP_AccountTabExt();
            String q = 'SELECT Name FROM ACCOUNT LIMIT 1';
            ApexPages.StandardSetController ACC = new ApexPages.StandardSetController(Database.getQueryLocator(q));
            List<SelectOption> ListViews = ACC.getListViewOptions();
            System.assertEquals(ListViews , acExtController.getAccountExistingViews());
            List<Account> accounts = [Select Id, Name, AccountNumber, ShippingStreet, ShippingCity, ShippingState, 
                                     ShippingCountry FROM Account ORDER BY Name ASC LIMIT 10000];
            System.assertEquals(accounts , acExtController.getAccounts());
            PageReference expectedPage = Page.CP_AccountDetail;
            String nextPage = acExtController.AccountDetailPage;
            System.assertEquals(expectedPage.getUrl(), nextPage); 
            acExtController.resetFilter();
            acExtController.prev();
            acExtController.next();
            acExtController.lastPage();
            acExtController.firstPage();
            
        }	
    }
	static testMethod void testNext()}{
		GenerateData();
		system.runAs(userCPU){
            PageReference pageref = Page.CP_AccountTab;
            Test.setCurrentPage(pageRef);
            ApexPages.StandardController controller = new ApexPages.StandardController(parentAccount);
            CP_AccountTabExt acExtController = new CP_AccountTabExt();
		}
		system.runAs(userCPM){
            PageReference pageref = Page.CP_AccountTab;
            Test.setCurrentPage(pageRef);
            ApexPages.StandardController controller = new ApexPages.StandardController(parentAccount);
            CP_AccountTabExt acExtController = new CP_AccountTabExt();
		}
	
	}
	static testMethod void testPrev(){
		GenerateData();
		system.runAs(userCPU){
            PageReference pageref = Page.CP_AccountTab;
            Test.setCurrentPage(pageRef);
            ApexPages.StandardController controller = new ApexPages.StandardController(parentAccount);
            CP_AccountTabExt acExtController = new CP_AccountTabExt();
		}
		system.runAs(userCPM){
            PageReference pageref = Page.CP_AccountTab;
            Test.setCurrentPage(pageRef);
            ApexPages.StandardController controller = new ApexPages.StandardController(parentAccount);
            CP_AccountTabExt acExtController = new CP_AccountTabExt();
		}	
	
	}
    static testMethod void testLast(){
		GenerateData();
		system.runAs(userCPU){
            PageReference pageref = Page.CP_AccountTab;
            Test.setCurrentPage(pageRef);
            ApexPages.StandardController controller = new ApexPages.StandardController(parentAccount);
            CP_AccountTabExt acExtController = new CP_AccountTabExt();
		}
		system.runAs(userCPM){
            PageReference pageref = Page.CP_AccountTab;
            Test.setCurrentPage(pageRef);
            ApexPages.StandardController controller = new ApexPages.StandardController(parentAccount);
            CP_AccountTabExt acExtController = new CP_AccountTabExt();
		}
	
	}
	static testMethod void testFirst(){
		GenerateData();
		system.runAs(userCPU){
            PageReference pageref = Page.CP_AccountTab;
            Test.setCurrentPage(pageRef);
            ApexPages.StandardController controller = new ApexPages.StandardController(parentAccount);
            CP_AccountTabExt acExtController = new CP_AccountTabExt();
		}
		system.runAs(userCPM){
            PageReference pageref = Page.CP_AccountTab;
            Test.setCurrentPage(pageRef);
            ApexPages.StandardController controller = new ApexPages.StandardController(parentAccount);
            CP_AccountTabExt acExtController = new CP_AccountTabExt();
		}
	}
    }



public with sharing class CP_AccountTabExt {

  /*** Instance Variables ***/

  public String AccountFilterId { get; set;}
  private String query = 'Select Id, Name, AccountNumber, ShippingStreet, ShippingCity, ShippingState, ShippingCountry FROM Account ORDER BY Name ASC LIMIT 10000';    
    private Integer pageSize = 50;
  
    /*** Static Variables (Static) ***/
    
    /*** Constant Variables (Static Final) ***/    
      
    /*** Public Instance Methods ***/
  public CP_AccountTabExt(){}
  
  public String AccountDetailPage {
    get{
            if(AccountDetailPage == null){
        PageReference accountDetail = Page.CP_AccountDetail;
                return accountDetail.getURL();
      }
      return '';
    }
    Set;
  }  

  public ApexPages.StandardSetController AccountSetController {
        get{
            if(AccountSetController == null){
                AccountSetController = new ApexPages.StandardSetController(Database.getQueryLocator(query));
                AccountSetController.setPageSize(pageSize);

                // We have to set FilterId after Pagesize, else it will not work
                if(AccountFilterId != null)
                {
                  AccountSetController.setFilterId(AccountFilterId);
                }
            }
            return AccountSetController;
        }set;
    }

  public CP_AccountTabExt(ApexPages.StandardSetController ssc) {  }

    //Navigate to first Page
    public void firstPage()
    {
      AccountSetController.first();
    }

    //Navigate to last Page
    public void lastPage()
    {
      AccountSetController.last();
    }

    //Navigate to Next page
    public void next()
    {
      if(AccountSetController.getHasNext())
      {
        AccountSetController.next();
      }
    }

    //Navigate to Prev Page
    public void prev()
    {
      if(AccountSetController.getHasPrevious())
      {
        AccountSetController.previous();
      }
    }

    public List<Account> getAccounts()
    {
      return (List<Account>)AccountSetController.getRecords();
    }

    //Get all available list view for Account
    public SelectOption[] getAccountExistingViews(){
        return AccountSetController.getListViewOptions();
    }

    /**
    * Reset List View
    */
    public PageReference resetFilter()
    {
      AccountSetController = null;
        AccountSetController.setPageNumber(1);
        return null;
    }
   
    
}

This will be a big help as I am new to salesforce test class.
Hi I want to know about the schedule apex ? How to write the schedule apex classes?