Hi am new to salesforce , how to do code coverage for this class - page reference method is written. below is the code:

public with sharing class AttachmentController {
    public Attachment attachObj {get;set;}

    public AttachmentController(){
        attachObj = new Attachment();

    public PageReference saveAttachment() {
        attachObj.ParentId = 'a0c410000055VT5AAM'; //  parent record id for an Attachment
        try {
            insert attachObj;
        }catch (Exception e) {
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,e.getMessage()));
            return null;

        ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Attachment uploaded successfully'));
        return null; 

A sample test method structure is given below. You can use a similar structure.

 * Test Sample Page
@isTest static void testSamplePage() {
    // TODO Set up the initial data needed for the test


        PageReference pageRef = Page.<<Page Name>>; // TODO Give the Page of the Controller

        // TODO Verify the Logic 
        AttachmentController ctrl = new AttachmentController();

        // TODO Assert Statements to Validate Behaviour
        System.assert(ctrl.saveAttachment() == null);   


| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.