+ Start a Discussion
daniel1110daniel1110 

help writing unit test

Hi. I'm new to force and having some trouble writing proper unit test for my trigger. The goal of this trigger is to attach a pdf to Notes & Attachments object. I would appreciate any help to get started in the right direction. I read the tutorials on writing unit tests, but still having problems.

Trigger:

trigger AttachAgreement on Opportunity (after insert) {
if(trigger.new[0].RecordTypeId=='012E0000000UMzBIAW')
{
    OpportunityPDFGenerator1.generateClientAgreementPDF(trigger.new[0]);
}
}

Class:

public with sharing class OpportunityPDFGenerator1
{
    
    public static final String FORM_HTML_START = '<HTML><BODY>';
    public static final String FORM_HTML_END = '</BODY></HTML>';
 
    public static void generateClientAgreementPDF(Opportunity opp)
    {
        datetime myDT = Datetime.now();
        String myDate = myDT.format('h:mm a');
        
        String pdfContent = '' + FORM_HTML_START;
        try
        {
            pdfContent = '' + FORM_HTML_START;
            pdfContent = pdfContent + 'body message goes here';
            pdfContent = pdfContent + FORM_HTML_END;
        }catch(Exception e)
        {
            pdfContent = '' + FORM_HTML_START;
            pdfContent = pdfContent + '<P>THERE WAS AN ERROR GENERATING PDF: ' + e.getMessage() + '</P>';
            pdfContent = pdfContent + FORM_HTML_END;
        }
        attachPDF(opp,pdfContent);
    }
    
    public static void attachPDF(Opportunity opp, String pdfContent)
    {
        try
        {
            Attachment attachmentPDF = new Attachment();
            attachmentPDF.parentId = opp.Id;
            attachmentPDF.Name = 'EnrollmentAgreement.pdf';
            attachmentPDF.body = Blob.toPDF(pdfContent); //This creates the PDF content
            insert attachmentPDF;
        }catch(Exception e)
        {
            opp.addError(e.getMessage());
        }
    }
    
}

 

Best Answer chosen by Admin (Salesforce Developers) 
Vinit_KumarVinit_Kumar

Hi Daniel,

 

Try below :-

 

@IsTest(SeeAllData=true)
Public class AttachAgreement_test{

static testmethod void MyUnittest(){

Opportunity opp = new Opportunity(Name='Test opp',CloseDate=system.today(),StageName='Prospecting',RecordTypeId='012E0000000UMzBIAW');// You need to populate all the mandatory field to insert opportunity record

insert opp;

}
}

All Answers

Vinit_KumarVinit_Kumar

Hi Daniel,

 

Try below :-

 

@IsTest(SeeAllData=true)
Public class AttachAgreement_test{

static testmethod void MyUnittest(){

Opportunity opp = new Opportunity(Name='Test opp',CloseDate=system.today(),StageName='Prospecting',RecordTypeId='012E0000000UMzBIAW');// You need to populate all the mandatory field to insert opportunity record

insert opp;

}
}

This was selected as the best answer
daniel1110daniel1110
vinit_kumar - thank u, ur awesome!
Vinit_KumarVinit_Kumar

Daniel,

 

Happy to help !!