+ Start a Discussion
Chase MaldonadoChase Maldonado 

Apex Test Class Troubles

I have followed numerous guides on creating Apex Test Classes, however I am using the class to reference data on my LWC and I am unsure how to go about testing.

Please see current Apex Code:
public class AccountContactController{
      
    @AuraEnabled(cacheable=true)
    public static List<AccountContactListWrapper> getAllAccountWithContacts(string searchKey){
        string searchKeyword = '%' + searchKey + '%';
        List<AccountContactListWrapper> accWrapperList = new List<AccountContactListWrapper>();
        List<Account> accList = [SELECT Id, Name, 
                                (SELECT Id, Name, Email, Phone, Title FROM Contacts), 
                                (SELECT Id, Name, Region_picklist__c, Total_Units__c FROM ChildAccounts) 
                                FROM Account WHERE Active__c = TRUE AND RecordTypeId = '0122K000001Dio1QAC' ORDER BY Name];
        if(!accList.isEmpty()){
            for(Account acc : accList){
                AccountContactListWrapper accWrapper = new AccountContactListWrapper();
                accWrapper.accRecord = acc;
                accWrapper.contactList = acc.Contacts;
                accWrapper.contactCount = acc.Contacts.size();
                accWrapper.NumberOfChildAccounts=acc.ChildAccounts.size();
                accWrapperList.add(accWrapper);
            }
        }
        return accWrapperList;
    }
    
    // wrapper class with @AuraEnabled and {get;set;} properties 
    public class AccountContactListWrapper{
        @AuraEnabled
        public Account accRecord{get;set;}
        @AuraEnabled
        public List<Contact> contactList{get;set;}
        @AuraEnabled
        public Integer contactCount{get;set;}
        @AuraEnabled
        public Integer NumberOfChildAccounts{get;set;}
    }
}

Can anyone help guide me on the proper method to testing this code so that we can push it to production with over 75% coverage?
Best Answer chosen by Chase Maldonado
Maharajan CMaharajan C
Hi Chase,

It's my mistake... I refered the apex class name insde test class...Try the below code and you will see the coverage...

The below line needs the change...

AccountContactController1.getAllAccountWithContacts('Test'); =====>  AccountContactController.getAllAccountWithContacts('Test');
@isTest
public class AccountContactControllerTest {
    static testmethod void getAllAccountWithContacts(){
        
        //Add below if there is any other mandatory fields are required to create Account 
        Account acc = new Account(name='Test Account', Active__c = TRUE , recordTypeId = '0122K000001Dio1QAC');   
        insert acc;
        
        //Add below if there is any other mandatory fields are required to create Contact         
        Contact con = new Contact(LastName = 'Test Con',AccountId = acc.Id);
        insert con;
        
        Test.startTest();
        AccountContactController.getAllAccountWithContacts('Test');
        Test.stopTest();
    }
}

Thanks,
Maharajan.C

All Answers

RohitJRohitJ
Hi Chase,

There is nothing different that you would need to do while writing test class for an AuraEnabled method. You would need to write the test class in same manner as you would do for any apex class.

Can you please put your test class code here, so we can check and suggest.

Thanks,
Rohit
Chase MaldonadoChase Maldonado
Hello Rohit,

Thank you for your help. If I understand you correctly, then all we need is to recreate the same apex class as a test class an run it. Here is the test class code:
@isTest
private class AccountContactController {
      
            @AuraEnabled(cacheable=true)
            public static List<AccountContactListWrapper> getAllAccountWithContacts(string searchKey){
                string searchKeyword = '%' + searchKey + '%';
                List<AccountContactListWrapper> accWrapperList = new List<AccountContactListWrapper>();
                List<Account> accList = [SELECT Id, Name, 
                                        (SELECT Id, Name, Email, Phone, Title FROM Contacts), 
                                        (SELECT Id, Name, Region_picklist__c, Total_Units__c FROM ChildAccounts) 
                                        FROM Account WHERE Active__c = TRUE AND RecordTypeId = '0122K000001Dio1QAC' ORDER BY Name];
                if(!accList.isEmpty()){
                    for(Account acc : accList){
                        AccountContactListWrapper accWrapper = new AccountContactListWrapper();
                        accWrapper.accRecord = acc;
                        accWrapper.contactList = acc.Contacts;
                        accWrapper.contactCount = acc.Contacts.size();
                        accWrapper.NumberOfChildAccounts=acc.ChildAccounts.size();
                        accWrapperList.add(accWrapper);
                    }
                }
                return accWrapperList;
            }
            
            // wrapper class with @AuraEnabled and {get;set;} properties 
            public class AccountContactListWrapper{
                @AuraEnabled
                public Account accRecord{get;set;}
                @AuraEnabled
                public List<Contact> contactList{get;set;}
                @AuraEnabled
                public Integer contactCount{get;set;}
                @AuraEnabled
                public Integer NumberOfChildAccounts{get;set;}
            }
}

I ran this test in VSCode and received the following results:
=== Test Summary
NAME                 VALUE                        
───────────────────  ─────────────────────────────
Outcome              Skipped                      
Tests Ran            0                            
Pass Rate            0%                           
Fail Rate            0%                           
Skip Rate            0%                           
Test Run Id          7077c000024N2eK              
Test Execution Time  0 ms                         
Org Id               00D7c000008sFRFEA2           
Username             cbm@zrsmanagement.com.partial


=== Test Results
12:28:29.935 ended SFDX: Run Apex Tests

Apologies, this is my first time running one of these. Thank you for any assistance you can provide.

Best Regards,
Chase
Maharajan CMaharajan C
Hi Chase,

You have to create new Apex test class with sample data in code to test our actual code.

Please create new test class with below code then run the below code to cover your actual class:
 
@isTest
public class AccountContactControllerTest {
    static testmethod void getAllAccountWithContacts(){
        
        //Add below if there is any other mandatory fields are required to create Account 
        Account acc = new Account(name='Test Account', Active__c = TRUE , recordTypeId = '0122K000001Dio1QAC');   
        insert acc;
        
        //Add below if there is any other mandatory fields are required to create Contact         
        Contact con = new Contact(LastName = 'Test Con',AccountId = acc.Id);
        insert con;
        
        Test.startTest();
        AccountContactController1.getAllAccountWithContacts('Test');
        Test.stopTest();
    }
}

Thanks,
Maharajan.C
Chase MaldonadoChase Maldonado
Hi Maharajan,

I set this up and ran the test but I get this error:
 
This class name's value is invalid: AccountContactControllerTest. Provide the name of an Apex class that has test methods.
15:17:08.91 Starting SFDX: Run Apex Tests

I looked on the forums and this seems like a common issue but I cannot find a fix or workaround. Any assistance would be helpful.

Thank you,
Chase
Maharajan CMaharajan C
Hi Chase,

It's my mistake... I refered the apex class name insde test class...Try the below code and you will see the coverage...

The below line needs the change...

AccountContactController1.getAllAccountWithContacts('Test'); =====>  AccountContactController.getAllAccountWithContacts('Test');
@isTest
public class AccountContactControllerTest {
    static testmethod void getAllAccountWithContacts(){
        
        //Add below if there is any other mandatory fields are required to create Account 
        Account acc = new Account(name='Test Account', Active__c = TRUE , recordTypeId = '0122K000001Dio1QAC');   
        insert acc;
        
        //Add below if there is any other mandatory fields are required to create Contact         
        Contact con = new Contact(LastName = 'Test Con',AccountId = acc.Id);
        insert con;
        
        Test.startTest();
        AccountContactController.getAllAccountWithContacts('Test');
        Test.stopTest();
    }
}

Thanks,
Maharajan.C
This was selected as the best answer
Chase MaldonadoChase Maldonado
Hello Maharajan,

Unfortunately this still did not fix the issue. We still get the error when we remove the 1 from the test:
This class name's value is invalid: AccountContactControllerTest. Provide the name of an Apex class that has test methods.

To confirm, the public class that is set up needs to be the same name as the test class itself right?
Example of VSC file
Maharajan CMaharajan C
Did you deployed the test class in your org...if noy yet done then first deploy the test class in your org...once you deployed then please verify once the test class is there or not in Salesforce from setup -> apex class or using developer console...you can directly run the test class from Salesforce UI or developer console...

First deploy the actual class and test class in your Salesforce org...
Chase MaldonadoChase Maldonado
Thank you so much! I feel silly for not checking to make sure this was deployed. Once deployed the test ran perfectly with 100% coverage.

I wanted to confirm the acts of the test, since I am newer and want to make sure that in the future I understand what to do.

First, we create a test account and then insert that into the class to make sure that the apex code finds it?
Second, we create a test contact to run the same as the account.
Third, we start the test for the class listed and then stop the test.

Is this correct how I am understanding it?