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
Akiko KoizumiAkiko Koizumi 

test code for try - catch block

Hi there,

I'm a beginner of VF code writing, and just managed to write a save button which redirects to the current page if any error, otherwise a different page, by coping the codes from https://salesforce.stackexchange.com/questions/194830/how-to-stop-firing-oncomplete-if-save-action-has-errors.
Then, I'm now trying to write the testing code but cannot cover the below part which prevents me to get 75% coverage.

Your kind guidance how to write test code covering the below would be highly appreciated!!


-------------------------------------------------------
public PageReference submit()
   {
     try {
            //navigate to view page
            PageReference pg = new PageReference('/'+ '0019000001UwnVS');
            pg.setRedirect(true);
            return pg;
     } catch (Exception ex) {
            System.debug('Error in submit ' + ex);
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.Error, ex.getMessage());
            ApexPages.addMessage(msg);
            return null;
}
}
----------------------------------------------------

Many thanks for your time and help.
Regards,
Akiko
Avishek Nanda 14Avishek Nanda 14
Hey Akiko,

It's very simple. Initiate the Controller and Call the Method in your test Class.

So test Class should go something like this 

PageReference pageRef = new PageReference('/'+ '0019000001UwnVS'); // Add your VF page Name here
        Test.setCurrentPage(pageRef);

Regards,
Avishek

Hope this helps. Mark this as the best answer if it helps. 
MagulanDuraipandianMagulanDuraipandian
Check this - http://www.infallibletechie.com/2015/11/how-to-write-code-for-try-catch-in-test.html