function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Sauhard Nandan ChaurasiaSauhard Nandan Chaurasia 

How to write test class for file upload?

Hi, novice here.

I have a Contact module on which I upload files(generally images) from the default File upoading function(PFA). I have used an after insert trigger to generate public url and made it visible. Then this URL is saved in a custom field of Contact module. It works fine. But when I write test class for this process, it doesn't work. Upon investigationl l found that the SObject it gives is 'User' for some reason, even though I linked it to a contact. I am sharing the original trigger code as well as test class for it. What am I doing wrong? Please guide.

Trigger 1-
trigger ContactFileLinkTrigger on ContentDocumentLink (before insert) {

    if(Trigger.isBefore){
        
        for(ContentDocumentLink l:Trigger.new) {
            l.Visibility='AllUsers';
        }
    }    
}
Trigger 2-
trigger ContactFileVersionTrigger on ContentVersion (after insert)
 {

    checkFileParent(trigger.New);
    
    public static void checkFileParent(List<ContentVersion> contentVersions){
       
        set<Id> contentDocumentIdSet = new set<Id>();
        map<Id, ContentVersion> contentDocumentIdVersionListMap = new map<Id, ContentVersion>();

        for(ContentVersion objContentVersion : contentVersions){
                    contentDocumentIdSet.add(objContentVersion.ContentDocumentId);
            contentDocumentIdVersionListMap.put(objContentVersion.ContentDocumentId, objContentVersion);
        }
		
        if(!contentDocumentIdSet.isEmpty())
        {
            List<ContentDocumentLink> contentDocumentList = [select LinkedEntityId, ContentDocumentId from ContentDocumentLink WHERE ContentDocumentId in :contentDocumentIdSet];

            system.debug('contentDocumentList: ' + contentDocumentList);
            
            if(contentDocumentList.size() > 0)
            {
                List<ContentVersion> validContentVersionList = new List<ContentVersion>();
                Map<Id, contact> versionIdContactIdMap = new Map<Id, contact>();
                for(ContentDocumentLink ContentDocumentSingle:contentDocumentList)
                {    
                    system.debug('ContentDocumentSingle: ' + ContentDocumentSingle.LinkedEntityId.getSObjectType().getDescribe().getName());
                    String documentSOject = ContentDocumentSingle.LinkedEntityId.getSObjectType().getDescribe().getName();
                    //if(documentSOject == 'Contact' || (Test.isRunningTest() && documentSOject == 'User') )
                    if(documentSOject == 'Contact')

                    {
                    	validContentVersionList.add(contentDocumentIdVersionListMap.get(ContentDocumentSingle.ContentDocumentId)); 
                        versionIdContactIdMap.put(contentDocumentIdVersionListMap.get(ContentDocumentSingle.ContentDocumentId).Id, [Select Contact_Image_URL__c, Contact_Image_Name__c FROM Contact WHERE id=:ContentDocumentSingle.LinkedEntityId LIMIT 1]);
                    }
                }
                
                if(validContentVersionList.size() > 0)
                {
                    createPublicLinkForFile(validContentVersionList, versionIdContactIdMap);
                }
            }
        }
    }
    
    public static void createPublicLinkForFile(List<ContentVersion> contentVersions, Map<Id, contact> versionIdContactIdMap)
    {
        ContentDistribution[] distributionsToInsert = new List<ContentDistribution>();
        set<Id> contentDistributionSet = new set<Id>();
        map<Id, ContentVersion> contentDistributionIdContentVersionMap = new map<Id, ContentVersion>();
       	for(ContentVersion objContentVersion : contentVersions){
            //if image uploaded then only create public link
            //if(objContentVersion.ContentDocumentId.ParentId.getSobjectType()==Contact.SobjectType){
                ContentDistribution getDist = createContentDistribution(objContentVersion.Id);
                //distributionsToInsert.add(createContentDistribution(objContentVersion.Id));
                distributionsToInsert.add(getDist);
            	system.debug('objContentVersion');
            	system.debug(objContentVersion);
            	contentDistributionIdContentVersionMap.put(objContentVersion.Id, objContentVersion);
                if(!contentDistributionSet.isEmpty())
                {
                    contentDistributionSet.clear(); 
                }
            	contentDistributionSet.add(objContentVersion.Id);
            //}
        }
        system.debug('distributionsToInsert: ' + distributionsToInsert);
        if(!distributionsToInsert.isEmpty())
        {
        	insert distributionsToInsert;
            List<ContentDistribution> contetDistributionList = [select ContentDownloadUrl, ContentVersionId from ContentDistribution WHERE ContentVersionId in :contentDistributionSet];
			
            system.debug('ContentDistribution: ' + contetDistributionList);
            system.debug('ContentDistribution url: ' + contetDistributionList[0].ContentDownloadUrl);
            
            List<contact> contactToUpdateList = new List<contact>();
            for(ContentDistribution contetDistributionsingle:contetDistributionList)
            {
                
                contact contactToUpdate = versionIdContactIdMap.get(contetDistributionsingle.ContentVersionId);
                
                contactToUpdate.Contact_Image_URL__c = contetDistributionsingle.ContentDownloadUrl;
                contactToUpdate.Contact_Image_Name__c = contentDistributionIdContentVersionMap.get(contetDistributionsingle.ContentVersionId).Title + '.' + contentDistributionIdContentVersionMap.get(contetDistributionsingle.ContentVersionId).FileType;
                
                contactToUpdateList.add(contactToUpdate);
            }
            
            if(contactToUpdateList.size() > 0)
            {
            	update contactToUpdateList;   
            }
        }
    }
    
    public static ContentDistribution createContentDistribution(Id contentVersionId){
        ContentDistribution newDist = new ContentDistribution();
        newDist.ContentVersionId = contentVersionId;
        newDist.Name = 'External Link';
        newDist.PreferencesNotifyOnVisit = false;
        newDist.PreferencesAllowViewInBrowser = true;
        newDist.PreferencesAllowOriginalDownload=true;
        system.debug('createContentDistribution created');
        system.debug(newDist);
        return newDist;
    }
}
I also tried to modify the code with SObject Type as User but then the test class just generates an error. (PFA)

Test Class (Excerpt code)-
@isTest
private class ContentDocumentLinkVisibilityHandlerTest {
    @isTest static void ContentDocumentLinkTriggerTest() {
        Test.startTest();
 
        Account accountObj = new Account();
        accountObj.Name = 'CRECAccount';
        INSERT accountObj;
        
        Contact contactObj = new Contact();
        contactObj.FirstName = 'CREC';
        contactObj.LastName = 'Project';
        contactObj.Email = 'abc@CERC.com';
        contactObj.AccountId = accountObj.Id;
        INSERT contactObj;
        
        ContentVersion content1 = new ContentVersion(); 
        content1.Title = 'Header_Picture1'; 
        content1.PathOnClient = '/' + content1.Title + '.jpg'; 
        Blob bodyBlob1 = Blob.valueOf('snc'); 
        content1.VersionData = bodyBlob1; 
        content1.origin = 'H';
        insert content1;
        ContentDocumentLink contentlink1 = new ContentDocumentLink();
        contentlink1.LinkedEntityId = contactObj.id; // linked with contact module
        contentlink1.contentdocumentid = [select contentdocumentid from contentversion where id =: content1.id].contentdocumentid;
        // contentlink1.ShareType = 'I';
        contentlink1.Visibility = 'AllUsers';
        insert contentlink1;
        Update contentlink1;
  
        Test.stopTest();
    }
}



upload image from this place
Error when change SObjectType to User in the trigger
Akshay SAkshay S
Hi Sauhard Nandan Chaurasia,

When we upload something Salesforce creates contentVersion record>contentDocument record and >2 contentDocumentLinks(One for sObject like-Account,Contact,Opportunity...,etc & Second for sObject User) records for each upload.
In your case when you are uploading something on Contact Salesforce creates two contentDocumentLinks on which targetObjectId field will have ContactId and UserId respectively.
Make sure you are fetching correct contentDocumentLink.

 
Akshay SAkshay S
+
Also, I would like to suggest you write after insert trigger on ContentDocumentLink instead of ContentVersion
Check for sObject API name whether it is User or Contact.
Then do further process.
It will simplify your test class as when you will run "after insert trigger on ContentDocumentLink" will fire and it will get two records one of User and another of contact 
In the main class, you are already checking API so it will take ContentDocumentLink record on which TargetObjectId is ContactId.