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.
If you still have Note and Attachments and you want to convert to Salesforce Files I recommend you install
Magic Mover for Notes And Attachments to Lightning Experience
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
One response to “How to create files in Salesforce for testing purposes”
You save my time! I use this on my test classes, thank you!