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
SadasivaSadasiva 

how to write test class for the attachments----urgent

hi ,

 

im working on to write test class, in that im facing problem to how to wrire test code for the attachment class. please provide solution for that.

 

 

thakyou.

Best Answer chosen by Admin (Salesforce Developers) 
BobBob

Bob, I found the problem. I had two controllers with the case object. I copied and pasted the case controller to create one for the account object and never changed the information in the code to the Account object.  I apoligize for the mis understanding and thank you very much for all your help. Now both test for the account and case object are covering 95%

 

Here is the final test code below.

@isTest
private class Test_BL_AccountFileUpload {

      static testMethod void testAttachments()
    {
        Account acc=new Account(Name='Acme Inc');
        insert acc;
        BL_AccountFileUpload controller=new BL_AccountFileUpload(new ApexPages.StandardController(acc));
 
        controller.fileName='Unit Test Attachment';
        controller.fileBody=Blob.valueOf('Unit Test Attachment Body');
        controller.uploadFile();
        
        List<Attachment> attachments=[select id, name from Attachment where parent.id=:acc.id];
        System.assertEquals(1, attachments.size());
    }
}

All Answers

bob_buzzardbob_buzzard

It would help if you posted your code.

 

However, testing attachments usually requires you to create something like the following:

 

 

static testMethod void testAttachments()
    {
    	Case cse=new Case();
        insert cse;
 
        Attachment attach=new Attachment();   	
    	attach.Name='Unit Test Attachment';
    	Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body');
    	attach.body=bodyBlob;
        attach.parentId=cse.id;
        insert attach;
    	
    	List<Attachment> attachments=[select id, name from Attachment where parent.id=:cse.id];
    	System.assertEquals(1, attachments.size());
    }

 

Obviously this is tied to cases, but hopefully gets you started.

 

BobBob

Hi I am trying to use your test method but I have zero lines covered. My extension is below. Any help on this issue would be greatly appreciated.

 

 

public class BL_CaseFileUpload  
{  
    ApexPages.StandardController sc = null;
      
   public BL_CaseFileUpload (ApexPages.StandardController ctlr)  
   {  
      sc = ctlr;             
    }  
      
    public string fileName   
    {    get;
         set {
           fileName = value;
            myAtt.name = value;
        }
   }  
      
   public Blob fileBody   
   {    get;
        set {
          fileBody = value;
            myAtt.body = value;
         }
    }    
    
    Attachment myAtt = new Attachment();
    
   public PageReference UploadFile()
{
    PageReference pr;

    Case css = (Case) sc.getRecord();
    upsert css;

    if(fileBody != null && fileName != null)
    {
      myAtt.ParentId = css.Id;
      insert myAtt;

      pr = new PageReference('/apex/vr_request_for_service_thank_you?Id='+ myAtt.Id);
      }
    else
    {
      pr = new PageReference('/apex/vr_request_for_service_thank_you'); // It will just redirect to this visualforce page.
      // You can redirect them to any page if you would like.
    }
    pr.setRedirect(true);
    return pr;

   }      
}

bob_buzzardbob_buzzard

That isn't a fully fledged test method - it was just showing what needs to be done to set up an attachment in a unit test.

 

You'll need to instantiate your controller, among other things. I think the following should be pretty close:

 

static testMethod void testAttachments()
    {
    	Case cse=new Case();
        insert cse;
        BL_CaseFileUpload controller=new BL_CaseFileUpload(new ApexPages.StandardController(cse));
 
    	controller.fileName='Unit Test Attachment';
    	controller.fileBody=Blob.valueOf('Unit Test Attachment Body');
        controller.uploadFile();
    	
    	List<Attachment> attachments=[select id, name from Attachment where parent.id=:cse.id];
    	System.assertEquals(1, attachments.size());
    }

 

BobBob

Close is right I have 95% coverage. Thank you so much I really appreciate your help!

BobBob

Now I am trying the same test on the account page. I converted the information to account, but it keeps giving me an error of invalid rutime conversion from runtime type SOBJECT:Account to SOBJECT Case even though I removed all the case info. Please see below and advise if possible.

 

static testMethod void testAttachments()
    {
        
        Account acc=new Account(Name='Acme Inc');
        insert acc;
        BL_AccountFileUpload controller=new BL_AccountFileUpload(new ApexPages.StandardController(acc));
 
        controller.fileName='Unit Test Attachment';
        controller.fileBody=Blob.valueOf('Unit Test Attachment Body');
        controller.uploadFile();
        
        List<Attachment> attachments=[select id, name from Attachment where Name=:acc.id];
        System.assertEquals(1, attachments.size());
    } 

bob_buzzardbob_buzzard

There's nothing in your test method that would cause that problem - can you post your revised page and controller.

BobBob

Bob, I found the problem. I had two controllers with the case object. I copied and pasted the case controller to create one for the account object and never changed the information in the code to the Account object.  I apoligize for the mis understanding and thank you very much for all your help. Now both test for the account and case object are covering 95%

 

Here is the final test code below.

@isTest
private class Test_BL_AccountFileUpload {

      static testMethod void testAttachments()
    {
        Account acc=new Account(Name='Acme Inc');
        insert acc;
        BL_AccountFileUpload controller=new BL_AccountFileUpload(new ApexPages.StandardController(acc));
 
        controller.fileName='Unit Test Attachment';
        controller.fileBody=Blob.valueOf('Unit Test Attachment Body');
        controller.uploadFile();
        
        List<Attachment> attachments=[select id, name from Attachment where parent.id=:acc.id];
        System.assertEquals(1, attachments.size());
    }
}

This was selected as the best answer
jsacpt24jsacpt24
Hello everyone. I am trying to do around the same thing but I cannot get my attachment part of my code to get to 75% (currently at 54% 12/22). Wondering if either of you could help me out? 

Class: 
public class case_attachment
{
public case objcase{get;set;}
public Attachment myAttachment{get;set;}
public string fileName{get;set;}
public Blob fileBody{get;set;}
 
    public case_attachment(Apexpages.standardcontroller controller)
    {
        objcase = (Case)controller.getRecord();
        myAttachment = new Attachment();
    }
    public pagereference save()
    {
      if(myAttachment.Name == null)
        {
        insert objcase;
        }
      if(myAttachment.Name != null)
      {
        insert objcase;
        System.debug('@@@@@fileBody'+fileBody);    
        myAttachment = new Attachment();
              Integer i=0;
              myAttachment .clear();
              myAttachment.Body = fileBody;
              myAttachment.Name = fileName ;
              myAttachment.ParentId = objcase.id;            
              insert myAttachment;   
        }             
        pagereference pr = Page.Thank_You;                          
        pr.setRedirect(true);
        return pr;
    }
}

TestClass: 
@isTest
private class Test_case_attachment {
    {
    	Case objcase=new Case();
        insert objcase;
 
        Attachment attach=new Attachment();   	
    	attach.Name='Test';
    	Blob bodyBlob=Blob.valueOf('Testing Body of Attachment');
    	attach.body=bodyBlob;
        attach.parentId=objcase.id;
        insert attach;
    	
    	List<Attachment> attachments=[select id, name from Attachment where parent.id=:objcase.id];
    	System.assertEquals(1, attachments.size());
    }

I was trying to use what you were using for the test class but it doesn't seem to like it. It seems that lines 5 & 6 as well as 21-29 are not being covered. Any assistance would be appreciated. 
 
bharath kuppalabharath kuppala
@RestResource(urlMapping='/ContactCRDID/*')
global with sharing class Ebuy_API
{
  @HttpGet
   global static List<Opportunity> doGet()
   {
      RestRequest request = RestContext.request;
        Integer ConCRD= Integer.valueof(request.requestURI.substring(request.requestURI.lastIndexOf('/')+1));
        List<Opportunity> result =  [Select StageName, PrimaryBPCRDID__c, Opportunnity_Source__c, OpportunityNumber__c, Name, 
                                     LastModifiedDate, Id, CreatedDate, Amount, Account.Name, CloseDate From Opportunity  
                                     where PrimaryBPCRDID__c =: ConCRD AND (((NOT StageName  LIKE '9-Closed%') AND 
                                     (NOT StageName  LIKE '8-Closed%')) OR (StageName  LIKE '8-Closed%' AND 
                                     CloseDate > LAST_N_MONTHS:1 )) ];  
       
       return result;
   }
 
}
Lesibe Manaka 3Lesibe Manaka 3
Please help me with this I would like to write and trigger using Salesforce best practise that will link all contacts from the related account that are flagged as key contacts to an opportunity on that account when it is created.

What i already did:

trigger OppCreatedKeyContactTrigger on Opportunity (after insert, after Update) {
    for(Opportunity opp : Trigger.New){

        if(Trigger.isInsert || Trigger.isUpdate){
            
            Contact con = [SELECT Id,Name,Key_Contact__c FROM Contact WHERE AccountId =:opp.AccountId];

            con.Key_Contact__c = true;
            update con;
            
        }
    }
}

I also need test class
Sakshi PawarSakshi Pawar
I want to cover this method


  @TestVisible
    @future(callout=true)
    private static void attachFile(Set<Id> expenditureListId)
    {
        //List to hold ContentDocumentLinks
        List<ContentDocumentLink> ContentDocumentLinkList  =  new List<ContentDocumentLink>();
        //Map to hold Expenditure Id and ContentVersion mapping
        Map<String,ContentVersion> expendContentVersionIdMap  =  new Map<String,ContentVersion>();
        
        //Query expenditure and map pdf according to recordType
        for(Expenditure__c expenditure: [Select Id, Recordtype.DeveloperName From Expenditure__c Where Id IN: expenditureListId]) 
        {
            PageReference paymentVoucherPDF =  Page.paymentVoucher;
            paymentVoucherPDF.getParameters().put('id',expenditure.Id);
            paymentVoucherPDF.setRedirect(true);
            Blob paymentVoucherBlob ;
            paymentVoucherBlob = paymentVoucherPDF.getContent();
            ContentVersion ContVerFile1 = new ContentVersion();
            ContVerFile1.VersionData = paymentVoucherBlob;
            ContVerFile1.Title = 'paymentVoucher'; 
            ContVerFile1.ContentLocation= 's';
            ContVerFile1.PathOnClient='paymentVoucher.pdf';
            expendContentVersionIdMap.put(expenditure.Id+'-'+ContVerFile1.Title, ContVerFile1);
            if(expenditure.Recordtype.DeveloperName == 'LTA_Reimbursement') {
                PageReference leaveTravelAllowancePDF =  Page.leaveTravelAllowance;
                leaveTravelAllowancePDF.getParameters().put('id',expenditure.Id);
                leaveTravelAllowancePDF.setRedirect(true);
                Blob leaveTravelAllowanceBlob ;
                leaveTravelAllowanceBlob = leaveTravelAllowancePDF.getContent();
                ContentVersion ContVerFile2 = new ContentVersion();
                ContVerFile2.VersionData = leaveTravelAllowanceBlob;
                ContVerFile2.Title = 'LeaveTravelAllowance'; 
                ContVerFile2.ContentLocation= 's';
                ContVerFile2.PathOnClient='LeaveTravelAllowance.pdf';
                expendContentVersionIdMap.put(expenditure.Id+'-'+ContVerFile2.Title, ContVerFile2);
            } else if(expenditure.Recordtype.DeveloperName == 'Travelling_Bill') {
                PageReference travelPaymentVoucherPDF =  Page.travelPaymentVoucher;
                travelPaymentVoucherPDF.getParameters().put('id',expenditure.Id);
                travelPaymentVoucherPDF.setRedirect(true);
                Blob travelPaymentVoucherBlob ;
                travelPaymentVoucherBlob = travelPaymentVoucherPDF.getContent();
                ContentVersion ContVerFile3 = new ContentVersion();
                ContVerFile3.VersionData = travelPaymentVoucherBlob;
                ContVerFile3.Title = 'TravelPaymentVoucher'; 
                ContVerFile3.ContentLocation= 's';
                ContVerFile3.PathOnClient='TravelPaymentVoucher.pdf';
                expendContentVersionIdMap.put(expenditure.Id+'-'+ContVerFile3.Title, ContVerFile3);
            } /*else if(expenditure.Recordtype.DeveloperName == 'Travelling_Bill') {
                PageReference travelPaymentVoucherPDF =  Page.travelPaymentVoucher;
                travelPaymentVoucherPDF.getParameters().put('id',expenditure.Id);
                travelPaymentVoucherPDF.setRedirect(true);
                Blob travelPaymentVoucherBlob ;
                travelPaymentVoucherBlob = travelPaymentVoucherPDF.getContent();
                ContentVersion ContVerFile3 = new ContentVersion();
                ContVerFile3.VersionData = travelPaymentVoucherBlob;
                ContVerFile3.Title = 'TravelPaymentVoucher'; 
                ContVerFile3.ContentLocation= 's';
                ContVerFile3.PathOnClient='TravelPaymentVoucher.pdf';
                expendContentVersionIdMap.put(expenditure.Id+'-'+ContVerFile3.Title, ContVerFile3);
            }    */              
        }
        
        // create contentDocumentLink 
        if(!expendContentVersionIdMap.isEmpty()) 
        {
            Insert expendContentVersionIdMap.values();
            
            List<ContentVersion> contVerList = [SELECT Id, ContentDocumentId FROM ContentVersion WHERE Id =:expendContentVersionIdMap.values()];
            
            for(String expenditureId: expendContentVersionIdMap.KeySet()) 
            {
                for(ContentVersion contVer : contVerList)
                {
                    if(contVer.Id == expendContentVersionIdMap.get(expenditureId).Id)
                    {
                        ContentDocumentLink cDe = new ContentDocumentLink();
                        cDe.ContentDocumentId = contVer.ContentDocumentId;
                        cDe.LinkedEntityId = expenditureId.split('-')[0];
                        cDe.ShareType = 'I';
                        cDe.Visibility = 'AllUsers';
                        ContentDocumentLinkList.add(cDe);
                        break;
                    }
                }
            }
            
            // Insert the ContentDocumentLink records
            
            if(!ContentDocumentLinkList.isEmpty()) 
            {
                Insert ContentDocumentLinkList;
            }
        }
    }

Please give the solution