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
Apex developer 21Apex developer 21 

Need some help on how to insert ContentDocumentLink in the correct way

@istest
public class TestNoteOnContentDocuments {
  static testmethod void NoteOnContentDoc(){
    ContentVersion contentVersion = new ContentVersion(
      Title = 'Penguins',
      PathOnClient = 'Penguins.jpg',
      VersionData = Blob.valueOf('Test Content'),
      IsMajorVersion = true
    );
    insert contentVersion;  
     

	List<ContentDocument> documents = [SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument];      
    
        ContentDocumentLink link=new ContentDocumentLink();
            link.LinkedEntityId=ContentDocumentLink.id;
            link.contentdocumentid=[select contentdocumentid from contentversion where id =:                  ContentDocument.id].contentdocumentid;
            link.ShareType = 'A';
   
        insert link;
 
      
     DmlException expectedException;
    Test.startTest();
        try { delete documents; }
        catch (DmlException dmx) { 
            
       Boolean expectedExceptionThrown = dmx.getMessage().contains('Approval pending. You do not have the permission to edit/delete this note/attachment, please contact your administrator.') ? true : false; 
       System.assertEquals(expectedExceptionThrown, true);  
        }
    Test.stopTest();
 }
}

 
Leo10Leo10
Hi 
You can refer this test class
@isTest(seealldata=true)
public class TestAttachmentHandler 
{
    static testMethod void validateHelloWorld()
    {
        
        Blob beforeblob=Blob.valueOf('Unit Test Attachment Body');

        ContentVersion cv = new ContentVersion();
        cv.title = 'test content trigger';      
        cv.PathOnClient ='test';           
        cv.VersionData =beforeblob;          
        insert cv;         

        ContentVersion testContent = [SELECT id, ContentDocumentId FROM ContentVersion where Id = :cv.Id];

        ContentDocumentLink contentlink=new ContentDocumentLink();
        contentlink.LinkedEntityId=ContentDocumentLink.id;
        contentlink.ShareType= 'V';
        contentlink.ContentDocumentId=testcontent.ContentDocumentId;

        insert contentlink;

        delete contentlink;

    }

}
Thank you
 
Swapnil PalSwapnil Pal
@Leo10 
1. seealldata=true is a very bad practice of writing test classes.
2. The setup of test data is not proper
3. No asserts present