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
sridhar sridharsridhar sridhar 

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

Hi, 

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

}catch(exception e){
            o=null;
            Apexpages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL, 'The URL entered is not exist.'));
            errorMessage=true;
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.remove(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)
        if(accounts.containsKey(record.AccountId))
            accounts.get(record.AccountId).Count_Contact__c++;
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

 

Thanks