-2

I want to cover catch block of getUserProfile method. I am providing the whole code, only catch block of getUserProfile method is not getting covered.

TestClass

@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 = testAccount.Id);
        Controllerclass.catchException = true;
        // Insert test data
        List<Partner_Task__c> tasks = new List<Partner_Task__c>{ task1, task2, task3, task4 };
        // Call the method to be tested
        
        Test.startTest();
        System.runAs(testALUser) {
            try{
                insert tasks;
            List<PartnerTasks.PartnerTaskWrapper> result = ControllerClass.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.');
                
            } catch(AuraHandledException e){
                System.assertEquals('Expected exception message', e.getMessage());
            }
            
            System.assertEquals(true, ControllerClass.catchException, 'Catch block was not exceuted');
    }
        Test.stopTest();
}
    
    @isTest 
    static void exceptionTest() {
        User testALUser = TestDataFactory.getTestUserPartner();
        String expectedErrorMsg = ControllerClass.APEX_ERROR;

        Test.startTest();
        //ControllerClass.testInstance = 3;
        ControllerClass.catchException= true;
        Partner_Task__c task3 = new Partner_Task__c(Name = 'Task 3', Status__c = 'In Progress',Account__c= Null);
        Partner_Task__c task4 = new Partner_Task__c(Name = 'Task 4', Status__c = 'Completed',Account__c= Null);
        List<Partner_Task__c> task = new List<Partner_Task__c>{task3, task4 };
        PartnerTasks.PartnerTaskWrapper check;
        Test.startTest();
            try {
                System.runAs(testALUser){
                    insert task;
                     List<PartnerTasks.PartnerTaskWrapper> result = ControllerClass.getCountTask();
                    PartnerTasks.PartnerTaskWrapper res = result[0];
                }
             } catch (Exception err) {
                System.assert(true, 'Expected error field to have message');
            }
            try {
                //System.runAs(testALUser){
                    List<Profile> result = ControllerClass.getUserProfile(); 
                //}
             } catch (Exception err) {
                System.assert(true, 'Expected error field to have message');
            }
        Test.stopTest();
    }
    
     @IsTest
     static void testGetUserProfileName() {

     User testALUser = TestDataFactory.getTestUserPartner();
     
     Controllerclass.catchException = true;
     Test.startTest();
     //System.runAs(testALUser) {
         try{
             List<Profile> result = ControllerClass.getUserProfile(); 
             //system.assert(false,'Expected expception was not thrown');
         }
         catch(AuraHandledException e){
                System.assertEquals('Expected exception message', e.getMessage());
             System.assertEquals(true, ControllerClass.catchException, 'Catch block was not exceuted');
            } 
        //System.assertEquals(true, ControllerClass.catchException, 'Catch block was not executed');       
    //}
    Test.stopTest();
}
}

Main Class -

public with sharing class ControllerClass {
    public class HomePageControllerException extends Exception{}
    private static final String CLASS_NAME = 'PartnerTaskController';
    @TestVisible private static Boolean catchException = false;
    @TestVisible private static final String APEX_ERROR = 'Error';
    
    @AuraEnabled(cacheable=true)
    public static List<PartnerTasks.PartnerTaskWrapper> getCountTask(){
        try{
            checkAndPerformExceptionTest();
            PartnerTasks ptask = new PartnerTasks();
            List<PartnerTasks.PartnerTaskWrapper> taskWrapper = ptask.getCountTask();
            return taskWrapper;
        }
        catch(Exception e){
            catchException = true;
            ApexErrorLogEvent.log(CLASS_NAME,'getCountTask',e); 
            throw new AuraHandledException(PartnerTaskConstants.Error_Occured);
        }    
    }
    
    private static void checkAndPerformExceptionTest() {
        if (Test.isRunningTest() && catchException == true) {
            throw new HomePageControllerException(APEX_ERROR);
        }
    }
    
    @AuraEnabled(cacheable=true)
    public static List<Profile> getUserProfile(){
        try{
            PartnerTasks ptask = new PartnerTasks();
            List<Profile> loggedInUserInfo = ptask.getUserProfile();
            return loggedInUserInfo;
        }
        catch(Exception e){
            catchException= true;
            ApexErrorLogEvent.log(CLASS_NAME,'getUserProfile',e); 
            throw new AuraHandledException(e.getMessage());
        }
    }
}

Query which is extracting the data-

public List<Profile> getCurrentUserProfile(System.AccessLevel accessLevel)
{
    if(accessLevel == System.AccessLevel.USER_MODE) 
    {   
        return [SELECT Id, Name FROM Profile WHERE Id =:userinfo.getProfileId() WITH USER_MODE];
    }
    else
    {
        return [SELECT Id, Name FROM Profile WHERE Id =:userinfo.getProfileId()];
    }   
}
3
  • salesforce.stackexchange.com/questions/350678/… Can you maybe have a look at this thread.
    – NedlaV
    Commented Jul 18, 2023 at 15:10
  • @NedlaV thanks, i am trying the same approach, one catch block is covering and other one is not. I might be missing something. My major guess is it is retrieving profile based on user id and since i can't insert user without profile, so not possible to throw exception. But this catch block is very much required otherwise i would have removed.
    – SF Learner
    Commented Jul 18, 2023 at 15:19
  • 1
    The first question to ask is "What catchable exception do you expect to be thrown here"? Once you establish why an exception will be thrown, you can attempt to devise logic to cause that exception to occur.
    – David Reed
    Commented Jul 18, 2023 at 16:19

1 Answer 1

0

I resolved it by running it as read only profile user.

@IsTest
 static void testGetUserProfileName() {
 User testALUser = TestDataFactory.getTestUserPartner();
 Controllerclass.catchException = true;
 Test.startTest();
 System.runAs(testALUser) {
     try{
         List<Profile> result = PartnerTaskController.getUserProfile(); 
     }
     catch(AuraHandledException e){
            System.assertEquals(true, PartnerTaskController.catchException, 'Catch block was not exceuted');
        }       
}
Test.stopTest();

}

@IsTest
static void testExceptionUserProfile(){
    Profile notALUser = [SELECT Id FROM Profile WHERE Name = 'APN Read Only' LIMIT 1];
    User testUser = new User(
        FirstName = 'Test',
        LastName = 'User112',
        Email = '[email protected]',
        Username = '[email protected]',
        Alias = 'test1222',
        ProfileId = notALUser.Id,
        EmailEncodingKey = 'UTF-8',
        LanguageLocaleKey = 'en_US',
        LocaleSidKey = 'en_US',
        TimeZoneSidKey = 'America/Los_Angeles'
    );
    insert testUser;
    
    Test.startTest();
    System.runAs(testUser){
        List<Profile> result = PartnerTaskController.getUserProfile(); 
    }
    Test.stopTest();
}

You must log in to answer this question.

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