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
Violeta Grigorova 3Violeta Grigorova 3 

Can you help me with a test class

I have a VF page and a Controller. I need to create an Apex Unit Test.

Here is the Controller:
 
public with sharing class ActiveSubscriptionsController {
    
    private ApexPages.StandardController stdController;
    private final Account acct;
	
   	public boolean show{get;set;}
    public boolean hide{get;set;}
   	public String DeviceId{get;set;}
    public String ContractNumber{get;set;}
    public String AccountNumber{get;set;}
    
    public ActiveSubscriptionsController(ApexPages.StandardController stdController) {
		this.stdController = stdController;
        this.acct = (Account)stdController.getRecord();
        AccountNumber = acct.AccountNumber;
        system.debug('Inside InvokeShow, AccountNumber: ' + AccountNumber);   
        show=true;
        hide=false;
    }

    public void InvokeShow(){
        show=false;
        hide=true;
		system.debug('Inside InvokeShow, DeviceId: ' + DeviceId);  
        system.debug('Inside InvokeShow, ContractNumber: ' + ContractNumber);
    }

    public void Invokehide(){
		show=true;
		hide=false;
    }
    
    public List<SBQQ__Subscription__c> getSubscriptions_front() {
        String AccountNumber = acct.AccountNumber;
        AccountNumber = AccountNumber + '%';
        String Empty = '';
        String AzureSubscription = '%Azure Subscription%';
        List<SBQQ__Subscription__c> subscriptionResults_front = 
        Database.query('SELECT Name, MasterDeviceName__c, SBQQ__ProductName__c, Location__c, DeviceId__c, SBQQ__ContractNumber__c, Server_Status__c  FROM SBQQ__Subscription__c WHERE DeviceId__c LIKE :AccountNumber AND (Location__c != :Empty OR SBQQ__ProductName__c LIKE :AzureSubscription)');
        return subscriptionResults_front;
    }
    
    public List<SBQQ__Subscription__c> getSubscriptions_filtered() {
        String Empty = '';
        List<SBQQ__Subscription__c> subscriptionResults_filtered = 
        Database.query('SELECT Name, SBQQ__ProductName__c, Location__c, DeviceId__c, SBQQ__ContractNumber__c, SBQQ__Contract__c, SBQQ__Account__c, SBQQ__RequiredByProduct__c, SBQQ__Product__c, SBQQ__ProductOption__c, SBQQ__OptionType__c, SBQQ__OrderProduct__c FROM SBQQ__Subscription__c WHERE DeviceId__c = : DeviceId AND SBQQ__ContractNumber__c  =: ContractNumber AND Location__c != :Empty');
        return subscriptionResults_filtered;
    }

    public List<SBQQ__Subscription__c> getSubscriptions_table() {
        String Empty = '';
        List<SBQQ__Subscription__c> subscriptionResults_table = 
        Database.query(
        'SELECT Name, DeviceId__c, SBQQ__ProductName__c, SBQQ__SpecialPrice__c, SBQQ__NetPrice__c, SBQQ__ProductOption__r.SBQQ__OptionalSKU__c, SBQQ__ProductOption__r.SBQQ__Selected__c, SBQQ__ProductOption__r.SBQQ__QuantityEditable__c, SBQQ__ProductOption__r.SBQQ__Quantity__c, SBQQ__ProductOption__r.SBQQ__MinQuantity__c, SBQQ__ProductOption__r.SBQQ__MaxQuantity__c, SBQQ__ProductOption__r.SBQQ__Number__c, SBQQ__ProductOption__r.ProductCategory__c,SBQQ__ProductOption__r.SBQQ__Feature__r.SBQQ__Category__c FROM SBQQ__Subscription__c WHERE DeviceId__c = : DeviceId AND SBQQ__ContractNumber__c  =: ContractNumber AND Location__c = :Empty ORDER BY SBQQ__ProductOption__r.SBQQ__Number__c');
        return subscriptionResults_table;
    }
    
    public Map<String, Map<String,List <SBQQ__Subscription__c>>> getMyMap () {
        String Empty = '';
        Map<String, Map<String,List <SBQQ__Subscription__c>>> myMap = new Map<String, Map<String,List <SBQQ__Subscription__c>>>();
        List<SBQQ__Subscription__c> subscriptionResults_4 = 
        Database.query('SELECT Name, DeviceId__c, SBQQ__ProductName__c, SBQQ__SpecialPrice__c, SBQQ__NetPrice__c, Location__c, SBQQ__ProductOption__r.SBQQ__OptionalSKU__c, SBQQ__ProductOption__r.SBQQ__Selected__c, SBQQ__ProductOption__r.SBQQ__QuantityEditable__c, SBQQ__ProductOption__r.SBQQ__Quantity__c, SBQQ__ProductOption__r.SBQQ__MinQuantity__c, SBQQ__ProductOption__r.SBQQ__MaxQuantity__c, SBQQ__ProductOption__r.SBQQ__Number__c, SBQQ__ProductOption__r.ProductCategory__c,SBQQ__ProductOption__r.SBQQ__Feature__r.SBQQ__Category__c FROM SBQQ__Subscription__c WHERE DeviceId__c = : DeviceId AND SBQQ__ContractNumber__c  =: ContractNumber AND Location__c = :Empty ORDER BY SBQQ__ProductOption__r.SBQQ__Number__c');
       
         for(SBQQ__Subscription__c sub: subscriptionResults_4){
			if(!myMap.containsKey(sub.SBQQ__ProductOption__r.SBQQ__Feature__r.SBQQ__Category__c)){
               myMap.put(sub.SBQQ__ProductOption__r.SBQQ__Feature__r.SBQQ__Category__c,new Map<String, List <SBQQ__Subscription__c>> {sub.SBQQ__ProductOption__r.ProductCategory__c => new List <SBQQ__Subscription__c>{sub}});
            }
			else {
                if(!myMap.get(sub.SBQQ__ProductOption__r.SBQQ__Feature__r.SBQQ__Category__c).containsKey(sub.SBQQ__ProductOption__r.ProductCategory__c)){
                    myMap.get(sub.SBQQ__ProductOption__r.SBQQ__Feature__r.SBQQ__Category__c).put(sub.SBQQ__ProductOption__r.ProductCategory__c,new List <SBQQ__Subscription__c>{sub});
				}
				else{
                    myMap.get(sub.SBQQ__ProductOption__r.SBQQ__Feature__r.SBQQ__Category__c).get(sub.SBQQ__ProductOption__r.ProductCategory__c).add(sub);
				}
            }
         }
         
        return myMap;
    }
}

Please let me know if you need any other information and thank you very much in advance!
Amit Chaudhary 8Amit Chaudhary 8
I will recommend you to start using trailhead to learn about test classes
1) https://trailhead.salesforce.com/modules/apex_testing

Also please check below post
1) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_qs_test.htm
2) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_example.htm

sample Test classes
1) http://amitsalesforce.blogspot.com/2015/06/best-practice-for-test-classes-sample.html

Test Class for you to start
@isTest 
public class ActiveSubscriptionsControllerTest 
{
	static testMethod void testMethod1() 
	{
		Account testAccount = new Account();
		testAccount.Name='Test Account' ;
		insert testAccount;
		
		/*
		SBQQ__Subscription__c sub = new SBQQ__Subscription__c();
		// Add all required field
		insert sub;
		*/
		
		Test.StartTest(); 
		
			ApexPages.StandardController sc = new ApexPages.StandardController(testAccount);
			ActiveSubscriptionsController  testAccPlan = new ActiveSubscriptionsController(sc);
			testAccPlan.InvokeShow();
			testAccPlan.Invokehide();
			testAccPlan.InvokeShow();
			
		Test.StopTest();
	}
}



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 .

Let us know if this will help you
Violeta Grigorova 3Violeta Grigorova 3
Hey, Amit, 

Thank yu very much! I started writing my own test cases, but I ended up having the following problem.

When I go to Setup -> Apex Classes, I could see code coverage percentage for some of the classes and for some I cannot. Do you know what is the reason behind this? Is there some specific setting I am missing ?

Thank you
Amit Chaudhary 8Amit Chaudhary 8
You need to write test classes for all test class which dnt have code coverage.
 
Raj VakatiRaj Vakati
@isTest
public class ActiveSubscriptionsControllerTest
{
 
   @isTest static void testMethodForException()//Checking Records for exception
    {
    Account testAccount = new Account();//Insert Account
        testAccount.Name='Test Account' ;
        insert testAccount;
		
		SBQQ__Subscription__c sub = new SBQQ__Subscription__c() ;
		sub.Name ='Test';
		insert sub ;
		
        ApexPages.StandardController sc = new ApexPages.StandardController(cont);
        ActiveSubscriptionsController subCon = new ActiveSubscriptionsController(sc);//Instantiate the Class
		subCon.InvokeShow();
		subCon.Invokehide();
		subCon.getSubscriptions_front();
		subCon.getSubscriptions_filtered();
		subCon.getSubscriptions_table();
		subCon.getMyMap();
		
		
         
    }
        
}

 
Violeta Grigorova 3Violeta Grigorova 3
Amit, I was under the impression that you should be able to see code coverage 0% if there is no test class. I mean there isn't even a field to specify the code coverage and I am not sure that even if I write the tests I would be able to see what percentage of the code has been covered for this specific class only.
Violeta Grigorova 3Violeta Grigorova 3
Anyways, thank you both very much for the help. That was my bad. Apparantly, the class page was too long and I was not able to see to the end of it, where the code coverage was. Thank you again! 
Amit Chaudhary 8Amit Chaudhary 8
There is one AppExchange app is also there which can you help for "Code Coverage Report in excel Format".
1) https://appexchange.salesforce.com/appxListingDetail?listingId=a0N3000000DXzlpEAD