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
GreenhornGreenhorn 

testing code in catch block

How can the code in catch block be covered under test ?

 

public void someMethod()  

{

    try
    {
         some code...
    }
    catch(Exception e)
    {
        some code - how to get test coverage for this code ?

        throw e;
    }

}

 

Thanks in advance!

Devendra@SFDCDevendra@SFDC

Hi,

 

Lets assume that you have a method to update a Account record.

 

I am giving a snippet of code to cover try/catch block inside test method.

 

To cover a catch block, you need identify the situation when your code invoke the catch block.

 

For example, the situation where object instance is not found. Therefore in the test method, I have deleted the account instance that i created and once again invoke the save method.

 

Try this:

private final Account acc;

public pagereference save()
{
	try
	{
		update acc;
	}
	catch(Exception e)
	{
		// some code;
	}
}


// Test code

static testMethod void Test_AccounUpdate()
{
	test.startTest();
	
	Account testAcc=new Account(Name='Test Account');
	insert testAcc;

	
	// Create instance of standard controller if you are using
	ApexPages.StandardController con = new ApexPages.StandardController(testAcc);

	// Now you can create instance of a class and invoke controller method
	AccountUpdateController ext= new AccountUpdateController();

	ApexPages.Pagereference result = ext.save(); // This will cover try block

	delete a; // Delete account record to cover catch block

	result = ext.save();
	
	test.stopTest();
} // End of test method

 Hope this helps :)

 

Thanks,

Devendra