How to create files in Salesforce for testing purposes

ContentVersion and ContentDocumentLink creation from Apex


May 21, 2021
featured image

Overview

The first question I asked myself when starting to write unit tests that involve files is: how do I upload files from my tests? "Upload" and unit tests doesn´t sound good Fortunately, dealing with files in Salesforce in a unit text context, is pretty easy.

Straight to the point

Instantiate a ContentVersion with a name, description and a small content. In this case I will create a TXT file to keep it simple.
      
ContentVersion cv = new ContentVersion();
cv.Description  = 'test description';
cv.PathOnClient ='test_file.txt';
cv.Title = 'test file '+DateTime.now();
cv.versiondata=Blob.valueOf('test file body');
insert cv;
     
    
After creating the file we want to relate to one or many existing records such as an Account, Opportunity or even a custom object record. To do that we have to insert a ContentDocumentLink
             
ContentDocumentLink cdl = new ContentDocumentLink();
cdl.ContentDocumentId = [SELECT Id, ContentDocumentId FROM ContentVersion WHERE Id =: cv.Id].ContentDocumentId;
cdl.LinkedEntityId ='ANY ID'; // <----- put your record id here, example: an account tid
cdl.ShareType = 'V';
insert cdl;

      
    

Now go to the associated record and see the file attachment. You will have to add the Files related list to the layout in case you don't have it yet.

Photo by Christin Hume on Unsplash


salesforce apex dev