How to create files in Salesforce for testing purposes

Reading Time: < 1 minutes

The first question I asked myself when starting to write unit tests that involve files is: how do I upload files from my tests? Fortunately, dealing with files in Salesforce in a unit test context, is pretty easy.

Creating unit tests in Salesforce is a great way to ensure accurate data and maintain the integrity of Salesforce’s software applications. In this post, we’ll take a look at how to quickly and easily create text files in Salesforce to use them in your unit tests.

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


About the author

Andrés Canavesi
Andrés Canavesi

Software Engineer with 15+ experience in software development, specialized in Salesforce, Java and Node.js.

Related posts

One response to “How to create files in Salesforce for testing purposes”

Leave a Reply

%d bloggers like this: