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
dinesh abcdinesh abc 

how to write test class for Aura enabled

public inherited sharing class LWCExampleController {
    @AuraEnabled(Cacheable = true)
    public static list<Account> fetchAccounts(String strObjectName) {
        if(String.isNotBlank(strObjectName)) {
            return Database.query('SELECT Id, Name, Industry From ' + strObjectName + ' limit 10');
        }
        else {
            return null;
        }
    }
}
SFDC Apex DevSFDC Apex Dev
@isTest
public static class testClass{
      static testmethod void test(){
           test.startTest();

           List<Account> accList = new List<Account>();
           Account acc = new Account(Name = 'Test Account');
           accList.add(acc);

           Account acct = new Account(Name = 'TestAccount');
           accList.add(acct);
           insert accList;

           String strObjectName = 'Object';
           LWCExampleController controller = new LWCExampleController();
           controller.fetchAccounts(strObjectName);

           test.stopTest();
      }
}

Try above test class.
Mark this as the best answer it will resolve your issue.

Thanks!
Chirag
Devi ChandrikaDevi Chandrika (Salesforce Developers) 
Hi Dinesh,
Test class for aura controllers is same as test classes for any other apex class.
Try this code
@isTest
public class testClass{
      static testmethod void fetchAccountstest(){
           test.startTest();
          
           Account acc = new Account(Name = 'unit test');
           insert acc;

           LWCExampleController.fetchAccounts('account');
           LWCExampleController.fetchAccounts('');

           test.stopTest();
      }
}

Please refer below link which might help you in this
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_qs_test.htm

​​​​​​​Hope this helps you
Let me know if this helps you. Kindly mark it as solved so that it may help others in future.

Thanks and Regards
sachinarorasfsachinarorasf
Hi Dinesh,

Try with this code.
 
@isTest
private class fetchAccounts_Test {
    @isTest static void getAccounts_Method(){
        Account accountObj = new Account();
        accountObj.Name = 'AccName';
        insert accountObj;
        
        Test.startTest();
        List<Account> result1 = LWCExampleController.fetchAccounts('Account');
        System.assertEquals(true,result1!=null);
        List<Account> result2 = LWCExampleController.fetchAccounts(null);
        System.assertEquals(true,result2==null);
        Test.stopTest();
        
    }

}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Sachin Arora