Tuesday 17 November 2020

How to prepare test data for Content Document Link (File)?

 Hi,

Here we are going to learn how can we prepare test data for Content Document.

Let's take a scenario that when a File is inserted under an Account record then "Count of files" should be calculated. (Solution: Apex Trigger on ContentDocumentLink)

Then the following test class will be useful for testing the above scenario.

To insert Content Document Link object record we have to insert ContentVersion first then retrieve the 

ContentDocument and then insert ContentDocumentLink object record.

@isTest

private class ContentDocumentLinkActionsTest {     

    testmethod static void insertContentDocumentTest(){       

        Account actObj = new Account();

actObj.Name = 'Salesforce Techbook';

insert actObj;

        //start insert a filer under Account 

ContentVersion content=new ContentVersion();

content.Title='Header_Picture1';

content.PathOnClient='/' + content.Title + '.jpg';

Blob bodyBlob=Blob.valueOf('Unit Test ContentVersion Body');

content.VersionData=bodyBlob;

content.origin = 'H';

insert content;

List<ContentDocument> documentsObj = [SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument

  where LatestPublishedVersionId=:content.Id];

ContentDocumentLink contentlink=new ContentDocumentLink();

contentlink.LinkedEntityId=actObj.id;

contentlink.contentdocumentid=[select contentdocumentid from contentversion where id =: content.id].contentdocumentid;

contentlink.ShareType = 'V';

Test.startTest();

insert contentlink;       

        Test.stopTest();

    }

}



No comments:

Post a Comment

How to include a screen flow in a Lightning Web Component

 Hi, Assume  you have a flow called "Quick Contact Creation" and API Name for the same is "Quick_Contact_Creation". To i...