+ Start a Discussion
Apex developer 21Apex developer 21 

How do i write a Unitest for Contentdocument

trigger NoteOnContentDocument on ContentDocument (before delete) {
    for (ContentDocument c : Trigger.old){
        List<ContentDocumentLink> links = [
            SELECT LinkedEntityId 
            FROM ContentDocumentLink 
            WHERE ContentDocumentId= :c.Id
        ];
        if (Approval.isLocked(links.get(1).LinkedEntityId)){
            c.addError('Approval pending. You do not have the permission to delete this note, Please contact your administrator.');
           }    
    }
}

 
Best Answer chosen by Apex developer 21
sachin sabusachin sabu
Ok try This
@istest
public class NoteOnContentDocument {
    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];
        try{
            delete documents;
        }
        catch(exception e){}
      
  }
}

 

All Answers

sachin sabusachin sabu
Hi,

Try this
@istest
public class NoteOnContentDocument {
    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];
        delete documents;
      
  }
}

 
Apex developer 21Apex developer 21
Hi sachin thanks for helpin i get:

09:33:50:461 EXCEPTION_THROWN [13]|System.DmlException: Delete failed. First exception on row 0 with id 0693E0000000TCqQAM; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, NoteOnContentDocument: execution of BeforeDelete

09:33:50:000 EXCEPTION_THROWN caused by: System.ListException: List index out of bounds: 1
sachin sabusachin sabu
Ok try This
@istest
public class NoteOnContentDocument {
    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];
        try{
            delete documents;
        }
        catch(exception e){}
      
  }
}

 
This was selected as the best answer