This post explains how to cover the apex try and catch block in salesforce.
Sometimes It becomes important to handle the catch block to complete 75 percent coverage in apex class. There are two lines of code you have to implement in apex class in order to cover both try and catch blocks.
- First you have to create a custom exception class.
- Use Test.isRunningTest() at the end of your try block. This statement will only run when you are running a test class.
- In Test.isRunningTest() throw a custom exception which you have created in earlier steps.
NOTE: The code is only based on that you want to cover both try and catch blocks.
SampleClass.apx :
public class SampleClass {
//create custom exception class
class MyException extends Exception{}
public static void Testing(){
try
{
String s = 'In try block';
system.debug(s);
// When test class is running it throw an exception
if(Test.isRunningTest())
{
throw new MyException();
}
}
catch(Exception e)
{
String s = 'In catch';
system.debug(s);
}
}
}
SampleClassTest.apx :
@isTestpublic class SampleClassTest { Public static testmethod void testSapIntegration(){ SampleClass.Testing(); }}
@isTest
public class SampleClassTest {
Public static testmethod void testSapIntegration(){
SampleClass.Testing();
}
}
Output :
Thanks,
Lovesalesforceyes
Lovesalesforceyes
No comments:
Post a Comment