+ Start a Discussion
sridhar sridharsridhar sridhar 

Catch block not able to get code coverage & Apexpages.Addmessage


I am not able to get code coverage for the the catch block.. 
how to get test code coverage for this. 

}catch(exception e){
            Apexpages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL, 'The URL entered is not exist.'));
Raghu NaniRaghu Nani
you need to pass wrong data ,in such a way that it should suppose to give error ,u need to call that specific method two times one is to cover try and next one is to cover catch
sridhar sridharsridhar sridhar
Thanks Raghu, 

Can you provide sample cod 
Anurag SaxenaAnurag Saxena
Hi Sridhar,
Not all code that is written can be covered. This is a fact of salesforce.com development. There is a reason why the deployment rule is 75% coverage, and not 100% coverage. This "wiggle room" exists so that developers can test the majority of their code, since exception handling can be hard to troubleshoot and even harder to test through scripting, since errors are supposed to be the exception, not the rule. The important thing about your test methods is that they verify your code works correctly. Unless you have a way of crafting a record that will fail, the only other method-- which is strongly not recommended-- would be to write a exception built into the actual code you're testing. This involves using Test.isRunningTest to set up an arbitrary failure
Here Is the Example-

trigger updateAccounts on Contact (after insert) {
    Map<Id, Account> accounts = new Map<Id, Account>();
    for(Contact record: Trigger.new)
        accounts.put(record.AccountId, null);
    accounts.putAll([SELECT Id,Count_Contact__c FROM Account WHERE Id IN :accounts.keySet()]);
    for(Account record: accounts.values())
        if(record.Count_Contact__c == null)
            record.Count_Contact__c = 0;
    for(Contact record: Trigger.new)
try {
        if(Test.isRunningTest() && globalFlags.crashTest) {  // Purposely crash test.
            accounts.values()[0].Id = null;
        update accounts.values();
    } catch(Exception e) {
        for(Contact record: Trigger.new)
            record.addError('Failed to update account');

Hope it will help you:)

Please choose as best answer