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
Jonathan Wolff 7Jonathan Wolff 7 

test Class for Content Document Trigger

Hello, I have build a trigger before delete on ContentDocument. Could you give me a code sample for the test class?



trigger DokumentenklasseDelete on ContentDocument (before delete) {

    
    map<id,ContentDocument> documentMap = new map<id,ContentDocument>([SELECT id,(SELECT Id,FileType,Dokumentenklasse__c from ContentVersions) from ContentDocument where id IN :trigger.old]);
 
        for(ContentDocument con : Trigger.old){
           List<ContentVersion> versionList = documentMap.get(con.Id).ContentVersions;
            if (versionList.size() > 0) {
                for (contentVersion cv : versionList) {
                    if(cv.Dokumentenklasse__c =='Geschäftsbrief' || cv.Dokumentenklasse__c == 'Vertragsdokument' || cv.Dokumentenklasse__c == 'Wichtige Dokumentation oder Entscheidung' ) {
                        con.adderror('Dokumente der Dokumentenklassen "Geschäftsbrief", "Vertragsdokument", "Wichtige Dokumentation oder Entscheidung" dürfen aus rechtlichen Gründen vor Ablauf der Aufbewahrungsfrist nicht gelöscht werden.');
                    }
                 }
            }
            
        }
ShivankurShivankur (Salesforce Developers) 
Hi Jonathan,

Check out below thread and example for reference:
https://developer.salesforce.com/forums/?id=9062I000000g4jOQAQ

You might need to write a test class in similar way with modification accordingly.

Also, check out below link to learn more about it:
https://trailhead.salesforce.com/content/learn/modules/apex_testing/apex_testing_intro

Hope above information helps. Please mark as Best Answer so that it can help others in future.

Thanks.
Jonathan Wolff 7Jonathan Wolff 7
Could you give me a help how the code for the test class could look like?
Jonathan Wolff 7Jonathan Wolff 7
Hi CharuDutt, sadly I get 0% coverage using this sample. Do you have an idea how to change it?
Greetings
Jonathan
Suraj Tripathi 47Suraj Tripathi 47

Hi,

Please find the solution.

@isTest
public class ContentDocumentTest{

public static testMethod void contentDocumentTest(){

/Create Document
ContentVersion cv = new ContentVersion();
cv.Title = 'Test Document';
cv.PathOnClient = 'TestDocument.pdf';
cv.VersionData = Blob.valueOf('Test Content');
cv.IsMajorVersion = true;
Insert cv;

//Get Content Version
List<ContentVersion> cvList = [SELECT Id, Title, ContentDocumentId FROM ContentVersion WHERE Id = :cv.Id];
System.assertEquals(cvList.size(), 1);

//Get Content Documents
List<ContentDocument> cdList = [SELECT Id, Title, LatestPublishedVersionId FROM ContentDocument];
System.assertEquals(cdList.size(), 1);
 delete cv;

}

}


Please mark it as the Best so that other people would take reference from it.

Thank You