You need to sign in to do that
Don't have an account?
Eric_Santiago
TestMethod for QueryException
I've got an issue with a test class. I'm stuck at 56% coverage. My test method creates all the objects referenced in my controller and works fine. When I run the tests, it tells me the whole catch (QueryException ex) section of the methods is not covered. Here's a sample of what I have so far.
Code:
public static Employee__c getEmployee() { try { Employee__c employee= [select id, kiosk__r.name, kiosk__c from Employee__c where user_name__c = :UserInfo.getUserId() Limit 1]; return employee; } catch (QueryException ex) { ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'No employee record found for current user!'); ApexPages.addMessage(myMsg); return null; } }
Code:
public static testMethod void testDashboardControllerMethods() { //create employee Employee__c employee1=new Employee__c(); employee1.Name='Test emp 1'; employee1.Emp_ID__c='xtyooyuoowow'; employee1.Kiosk__c=kiosk.Id; employee1.Quota_Status__c='Active'; employee1.Sys_ID__c='127uijo90'; employee1.User_Name__c=[Select Id from user where Isactive=true Limit 1].Id; employee1.Weekly_Hours__c=20; insert employee1; dashboardController.getEmployee(); }
I tried creating a QueryException in the test method by adding a second test method that creates a employee record but not specifying user_name__c.
Code:
public static testMethod void testDashboardControllerMethods2() { //test the exception errors Employee__c employee1=new Employee__c(); insert employee1; dashboardController.getEmployee(); }
That doesn't seem to work. Any suggestions?
canonw
I face the same issue when I work with UserInfo.getUserId(). This is the trick to increase the code coverage.
- Pass UserInfo.getUserId() value to a class variable (let's define it as string userId) Assign the value in the constructor.
- The SOQL should refer to userId for the user id.
- Create extra test case. Before calling dashboardController.getEmployee();, Set the userid that will gaurantee a call to the catch block.