0

I am able to cover try block of my main class, but failing to do the same for catch block. Here's the given code for my current test class and Main Class.

Controller Class-

public with sharing class PartnerTaskController {

@AuraEnabled(cacheable=true)
public static List<PartnerTasks.PartnerTaskWrapper> GetCountTask(){
    try{
        List<PartnerTasks.PartnerTaskWrapper> taskWrapper = PartnerTasks.getCountTask();
        system.debug('Main Controller '+taskWrapper);
        return taskWrapper;
    }
    catch(Exception e){
        ApexErrorLogEvent.log('PartnerTaskController','GetCountTask',e); 
        throw new AuraHandledException(e.getMessage());
    }
}

@AuraEnabled(cacheable=true)
public static List<Profile> GetUserProfile(){
    try{
        List<Profile> loggedInUserInfo = PartnerTasks.getUserProfile();
        system.debug('Controller User '+ loggedInUserInfo);
        return loggedInUserInfo;
    }
    catch(Exception e){
        ApexErrorLogEvent.log('PartnerTaskController','GetUserProfile',e); 
        throw new AuraHandledException(e.getMessage());
    }
}

PartnerTasks-

public static List<PartnerTaskWrapper> getCountTask(){
    
    List<PartnerTaskWrapper> taskWrapper = new List<PartnerTaskWrapper>();
    User userData= UserUtils.getCurrentUser();
    String accountId = userData.Contact.Account.Id;
    Integer countedOpenTasks = 0;
    Integer countedUnassignedTasks =0 ;
    Integer countedOverdueTasks = 0;
    Integer counted7DaysDueTasks =0;
    
    List<Partner_Task__c> ptask= PartnerTaskSelector.getAllCountTask(accountId, System.AccessLevel.SYSTEM_MODE);
   
    for(Partner_Task__c allTask: ptask){
        if(allTask.Status__c == PartnerTaskConstants.STRING_ASSIGNED ||
          allTask.Status__c == PartnerTaskConstants.STRING_INPROGRESS || 
           allTask.Status__c == PartnerTaskConstants.STRING_UNASSIGNED){
            countedOpenTasks ++;
        }
        if(allTask.Status__c == PartnerTaskConstants.STRING_UNASSIGNED){
            countedUnassignedTasks ++;
        }
        if(allTask.Task_due_in_days__c <0){
            countedOverdueTasks ++;
        }
        if(allTask.Task_due_in_days__c <= 7 && allTask.Task_due_in_days__c >= 0){
            counted7DaysDueTasks ++;
        }
    }
    taskWrapper.add(new PartnerTaskWrapper(countedOpenTasks,countedUnassignedTasks, countedOverdueTasks, counted7DaysDueTasks ));
    system.debug('days7dueCount '+counted7DaysDueTasks);
    system.debug('overdue '+countedOverdueTasks);
    system.debug('unassigned '+countedUnassignedTasks);
    system.debug('openCount '+countedOpenTasks);
    system.debug('wrapper '+ taskWrapper);
      return taskWrapper;
 }

PartnerTaskSelector -

public static List<Partner_Task__c> getAllCountTask(Id accountId, System.AccessLevel accessLevel){
    if(accessLevel == System.AccessLevel.USER_MODE) {
        return [SELECT Name, Status__c, Due_Date__c , Task_due_in_days__c from Partner_Task__c WHERE Status__c != :PartnerTaskConstants.STRING_COMPLETED AND Account__c = :accountId WITH USER_MODE ];
        
    }
    else {
        return [SELECT Name, Status__c, Due_Date__c , Task_due_in_days__c from Partner_Task__c WHERE Status__c != :PartnerTaskConstants.STRING_COMPLETED AND Account__c = :accountId ];
    }
}

PArtnerTaskControllerTest class-

@IsTest

private class PartnerTaskControllerTest {

    @isTest
static void testGetCountTask() {
    Account testAccount = TestDataFactory.getTestAccount();
    Contact testContact = new Contact(AccountId = testAccount.Id, LastName= 'Test Contact');
    insert testContact;
    User testALUser = TestDataFactory.getTestUserPartner();
    testALUser.ContactId = testContact.Id;
    // Create test data
    Partner_Task__c task1 = new Partner_Task__c(Name = 'Task 1', Status__c = 'Assigned',Account__c= testAccount.Id);
    Partner_Task__c task2 = new Partner_Task__c(Name = 'Task 2', Status__c = 'Unassigned',Account__c= testAccount.Id);
    Partner_Task__c task3 = new Partner_Task__c(Name = 'Task 3', Status__c = 'In Progress',Account__c= testAccount.Id);
    Partner_Task__c task4 = new Partner_Task__c(Name = 'Task 4', Status__c = 'Completed',Account__c = Null );
    // Insert test data
    List<Partner_Task__c> tasks = new List<Partner_Task__c>{ task1, task2, task3, task4 };
    List<Partner_Task__c> taskException = new List<Partner_Task__c>{task4};   
    // Call the method to be tested
    Test.startTest();
    System.runAs(testALUser) {
    //Test.setMock(AuraHandledException.class, new AuraHandledException_Mock());
    try {
        insert tasks;
        List<PartnerTasks.PartnerTaskWrapper> result = PartnerTaskController.GetCountTask();
        PartnerTasks.PartnerTaskWrapper wrapper = result[0];
        System.assertEquals(3, wrapper.countedOpenTasks, 'Should have open tasks if status is not completed yet.');
        System.assertEquals(1, wrapper.countedUnassignedTasks, 'Should have 1 unassigned tasks if due date is already passed.');
        System.assertEquals(0, wrapper.countedOverdueTasks, 'Should have overdue tasks if due date is already passed.');
        System.assertEquals(0, wrapper.counted7DaysDueTasks, 'Should have Tasks due within 7 days if due date is in next 7 days.');
        insert taskException;
        List<PartnerTasks.PartnerTaskWrapper> resultException = PartnerTaskController.GetCountTask();
    } catch (Exception e) {
        System.assert(true, 'Exception was thrown as expected');
    }
}
    Test.stopTest();

}

 @IsTest
 static void testGetUserProfileName() {

 User testALUser = TestDataFactory.getTestUserPartner();
 Test.startTest();
 System.runAs(testALUser) {
    // Call the method to be tested
    List<Profile> result = PartnerTaskController.GetUserProfile();   
}
Test.stopTest();
 }

}

In test class, as my query in main selector selecting the records which is having status as not completed and with any account Id. so I was thinking if i will create a record in test class with status completed and account id null, it would throw exception but it's not working. Even if exception statement is coming but it's not covering catch block.

3
  • So what you need to do is IN YOUR TEST insert a user with a system profile that DOES NOT have access to your fields and then use them in System.runAs() :)
    – zaitsman
    Jul 17, 2023 at 5:39
  • @zaitsman but i need to run it as 'testALUser' to cover correct part. How can I apply system.runAs for 2 users in a single method?
    – SF Learner
    Jul 17, 2023 at 7:12
  • @ueser19761995 just write TWO separate tests. One for correct part and ANOTHER for catch part
    – zaitsman
    Jul 17, 2023 at 10:37

1 Answer 1

0

If there is no way that those aura methods could ever throw exceptions, you need to rethink if you really need try catch block? If there is, then generate those scenarios for real unit test.

Another dirty way to have coverage of catch block,

  • have a dedicated test method just to cover exception
  • Declare a class level variable and mark it @TestVisible. e.g. private static boolean coverExceptionBlock; set it to true in test method.
  • Then in the beginning of each method generate exceptions conditionally
  • If (Test.isRunningTest() && coverExceptionBlock) { Integer i = 1/0; }
2
  • @Hermant Shukla or just make it happen by having a profile that throws exception on query (like Read Only profile)
    – zaitsman
    Jul 17, 2023 at 10:36
  • thanks this helped
    – SF Learner
    Jul 19, 2023 at 5:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .