Posted in Salesforce

Salesforce Apex : Writing Unit Test for ContentDocument

Salesforce’s SObject – ContentDocument supports only SELECT and DELETE operation. However INSERTing the document may be needed for writing Unit Tests which is not supported. There needs to be a workaround for it.

We can make use of ContentVersion SObject which creates a document for us. Following is the snippet to Test the INSERT and DELETE operation:

@isTest
public class <Controller_Name_here>Controller_AC_Test {
    @isTest static void <method_name_here>_Test()
    {
        ContentVersion contentVersionInsert = new ContentVersion(
            Title = 'Test',
            PathOnClient = 'Test.jpg',
            VersionData = Blob.valueOf('Test Content Data'),
            IsMajorVersion = true
        );
        insert contentVersionInsert;

        // Test INSERT
        ContentVersion contentVersionSelect = [SELECT Id, Title, ContentDocumentId FROM ContentVersion WHERE Id = :contentVersionInsert.Id LIMIT 1];
        List<ContentDocument> documents = [SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument];
        System.assertEquals(documents.size(), 1);

        // Test DELETE
        <Controller_Name_here>Controller_AC.deleteContentDocument(contentVersionSelect.ContentDocumentId);
        documents = [SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument];
        System.assertEquals(documents.size(), 0);
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s