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
Bryan TelfordBryan Telford 

Code Coverage for Exception

I am trying to get code coverage for an exception in my test class. I have the following code in the class.

  public void requestReport() {   
     currentuser=[Select Id, Name, Email from User where Id=:userinfo.getuserId()];
        try 
            {     
                SQL_Report_Request__c request = new SQL_Report_Request__c (Request_Type__c = 'Branches Directory', Email__c = currentuser.Email);
                insert request;    
            }
                catch(DmlException ex){
                ApexPages.addMessages(ex);
           } 
    }

My unit test tries to insert an invalid email address, i.e. "test1234.com". The test passes with 90% but does not cover the following in my class.
  catch(DmlException ex){
                ApexPages.addMessages(ex);
}

Here is my unit test.
private static testMethod void testReportRequestWithDMLException() {
    branchesListController controller = new branchesListController();
       // ARRANGE
       List<SQL_Report_Request__c> request = new List<SQL_Report_Request__c> {
            new SQL_Report_Request__c(Request_Type__c = 'Branches', Email__c = 'test1234.com')
        };

       
       // ACT 

          try {
        controller.requestReport();
        insert request;
        }
        catch(DmlException ex) {
             //Assert Error Message

           System.assertNotEquals(ex, null);
     
        }
Manish BhatiManish Bhati
try below test class:-
 
private static testMethod void testReportRequestWithDMLException() {
    branchesListController controller = new branchesListController();
       // ARRANGE
       List<SQL_Report_Request__c> request = new List<SQL_Report_Request__c> {
            new SQL_Report_Request__c(Request_Type__c = 'Branches', Email__c = 'test1234.com')
        };

       
       // ACT 

          try {
        controller.requestReport();
        insert request;
        }
        catch(DmlException ex) {
             //Assert Error Message

           System.assertNotEquals(ex, null);
     
        }
       delete request;
       delete request;

just put delete request twice.
Manage the parenthesis yourself.

Let me know if this works for you.
VineetKumarVineetKumar
Well this is a small hack that I put in my code to cover the exception part.
Below code need to be put in your actual code (but with caution and consideration).
if(Test.isRunningTest()){
    Integer errorCount = 0/0;
}
Let me know if that helped.