This question already has an answer here:

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; 

marked as duplicate by Eric, Raul, Mohith Shrivastava, Markus Slabina, glls Aug 21 '17 at 15:59

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


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);   



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