I think this is very straight forward I just can't figure out the issue behind it.

Error: : 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]

The Code:

public static ContentVersion createCV2(){
    ContentVersion cv=new Contentversion();
    cv.PathOnClient ='test';
    Blob b=Blob.valueOf('Unit Test Attachment Body');
    cv.versiondata=EncodingUtil.base64Decode('Unit Test Attachment Body');
    insert cv;
    return cv;

This is the one calling the method:

    List<Account> accountList = new List<Account>();
    accountList = TestDataFactory.createAccount('name', 1, true);
    String accountId = accountList[0].Id;
    List<Contact> contactList = new List<Contact>();
    contactList = TestDataFactory.createContact(USER_FIRSTNAME, USER_LASTNAME, 1, false);
    contactList[0].AccountId = accountId;
    contactList[0].Email = USER_EMAIL;
    insert contactList;
    String contactId = contactList[0].Id;
    List<User> userList = new List<User>();
    userList = TestDataFactory.createCommunityUser(USER_FIRSTNAME, USER_LASTNAME, contactId, USER_EMAIL, 1, true);

If it is being run as System admin , it works fine. But once run as a community user it is throwing the error...

  • Community user might not have access to the Object. You can just query an admin user or create an admin user and use System.runAs to run this test case with admin user. Commented Dec 10, 2020 at 4:08
  • What object? I am not associating the file to any object and just uploading it. I need to run this case as Community user due to some special scenarios. I am just currently stuck here at these line of code.
    – Snorlax
    Commented Dec 10, 2020 at 4:09
  • When you upload a file it creates ContentDocument, ContentDocumetLink and ContentVersion object in salesforce. Commented Dec 10, 2020 at 4:12
  • 1
    it is only failing in test class , it is working fine if tested it in the community and uploading file on the same profile
    – Snorlax
    Commented Dec 10, 2020 at 4:13
  • 1
    I would suggest to add the network ID as well while inserting content version and supply it in test class via query. (Network.getNetworkId won't get correct ID in test class)
    – manjit5190
    Commented Dec 11, 2020 at 3:19


You must log in to answer this question.

Browse other questions tagged .