2

I've written a simple trigger to enforce our Community users not to delete files. Currently, I'm facing an issue in getting test coverage for deployment.

Trigger

trigger ContentDocumentTrigger on ContentDocument (before delete) {
    if(trigger.isBefore){
        if(trigger.isDelete){
            ContentDocumentTriggerHelper helper = new ContentDocumentTriggerHelper();
            helper.preventFilesDeletion(Trigger.Old);
        }
    }
}

Helper Class

public class ContentDocumentTriggerHelper {
    public void preventFilesDeletion(List<ContentDocument> files){
        // Check whether logged in user is a Portal user
        User usr = [Select Id,Name,IsPortalEnabled from User where id=:UserInfo.getUserId()];
        //If it is portal user, trigger a validation saying - Attachments cannot be deleted
        if(usr.IsPortalEnabled){
            for(ContentDocument attmt: files){
                attmt.addError('Attachment cannot be deleted');
            }
        }
    }  
}

Test Class

@isTest
public class ContentDocumentTriggerHelperTest {

    static testMethod void ContentDocumentTest(){        
        user usr = [SELECT ContactId,Id,IsActive,IsPortalEnabled,contact.accountid FROM User WHERE IsActive = true AND IsPortalEnabled = true AND Usertype !='PowerPartner' LIMIT 1];
        
            system.runAs(usr){
                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;

                // Test insert
                List<ContentDocument> documents = [SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument];
                System.assertEquals(documents.size(), 1);
                // Test delete
                delete documents;
            }          
    }
}

This test class fails with this exception:

System.DmlException: Insert failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, You do not have the level of access necessary to perform the operation you requested. Please contact the owner of the record or your administrator if access is necessary.: [NetworkId]

What I've tried so far:

  1. Tried removing system.runas(): Test class passes, but gives only 60% coverage, it didn't pass through at if(usr.IsPortalEnabled).
  2. Tried setting contentVersion Owner - Getting this exception : System.DmlException: Insert failed. First exception on row 0; first error: INVALID_STATUS, Documents in a user's private library must always be owned by that user.: [OwnerId]
  3. Tried setting FirstPublishLocationId as stated here, getting this exception: System.DmlException: Insert failed. First exception on row 0; first error: INVALID_ID_FIELD, You must specify a FirstPublishLocation where you have publish permission.: [FirstPublishLocationId]

Is there any other approach, where I get through this? I think my question is a duplicate of this. Still, I've initiated a new conversation to see is there any solution?

Appreciate all your help!

6
  • Could you not simply set the usr as the owner of the data you create in this test?
    – Phil W
    Nov 10 '20 at 21:20
  • 2
    Hi @PhilW I've tried that, but no success. 1. When I set OwnerId I'm getting: System.DmlException: Insert failed. First exception on row 0; first error: INVALID_STATUS, Documents in a user's private library must always be owned by that user.: [OwnerId] 2. When I set FirstPublishLocationId I'm getting: System.DmlException: Insert failed. First exception on row 0; first error: INVALID_STATUS, Documents in a user's private library must always be owned by that user.: [OwnerId] Nov 10 '20 at 21:35
  • I suggest you edit the question to add these details as they are quite pertinent.
    – Phil W
    Nov 10 '20 at 21:36
  • Sure, Thanks @PhilW Nov 10 '20 at 21:37
  • Do you have more than one community as the NetworkId is the community id?
    – Dave Humm
    Nov 10 '20 at 22:08
3

I have a similar issue and this workaround helped me:

Id networkId = [SELECT Id FROM Network LIMIT 1].Id;

    System.runAs(portalUser) {
        
        ContentVersion contentVersion = new ContentVersion(
            Title = 'Test',
            PathOnClient = 'Test.jpg',
            VersionData = Blob.valueOf('Test Content Data'),
            IsMajorVersion = true,
            NetworkId = networkId
        );
        insert contentVersion;
}

So I just specified NetworkId in my test ContentVersion record.

2
  • 1
    This fixes the problem for me too. Confusing results at first from a unit test as I had Network.getNetworkId() to find the network Id but that seems to always return null in unit tests, hence the query approach is needed for unit tests.
    – Keith C
    Jan 18 at 19:11
  • Perfect! This saved me so much time, I could not figure out what was going on. Mar 17 at 21:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.