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
Carolyn julianaCarolyn juliana 

How to write Test class to test a field on an attachment or file insert?

Below is the trigger  update a field on an attachment or file insert , can some one suggest a test class for this trigger?

Can some one please help in writing a  @isTest class for below trigger to achieve 100 % code completion 
 
trigger ContentDocumentLinkTrigger on ContentDocumentLink (after insert) {
    if(trigger.isAfter) {
        if(trigger.isInsert) {
            ContentDocumentLinkTriggerHandler.onAfterInsert(trigger.new);
        }
    }
}

here is the class
public  class ContentDocumentLinkTriggerHandler {
   
public static void onAfterInsert(list<ContentDocumentLink> lstCntLinks) {
set<Id> setTaskIds = new set<Id>();
list<task> lstTask=new list<task>();
Id recordTypeId = Schema.SObjectType.Task.getRecordTypeInfosByName().get('Task_Record_Type').getRecordTypeId();

for(ContentDocumentLink clIterator : lstCntLinks) {  
     setTaskIds.add(clIterator.LinkedEntityId);//Set all task id            
 }

if(!setTaskIds.isEmpty()) {
                lstTask= [SELECT Id, Name,Attachment_Indicator__c  FROM task WHERE Id IN :setTaskIds and recordtypeid=: recordTypeId ]; //Get all the task 
            }

for(task varTsk:  lstTask){
varTsk.Attachment_Indicator__c=true;//Set Attachment Indicator Flag true

}
if(lstTask.size()>0){
update lstTask; //update task
         }
    }
}

Thanks in Advance,
Carolyn
Best Answer chosen by Carolyn juliana
SarvaniSarvani
Hi Carolyn,

In your apex class line 13, SOQL query remove name as there is no such standard field name on Task and it will give error. Try using below test class for 100% coverage.
@isTest public class ContentDocumentLinkTriggerhanlderTest {

  @isTest public static  void testmethod1(){
        Test.startTest();
    
    Id RecordTypeIdTask = [Select Name, Id From RecordType where sObjectType='Task' and isActive=true and name='Task_Record_Type'].id;

        Task T =new Task(Subject='New Test Task',Status='New',Priority='Normal', recordtypeid=RecordTypeIdTask);
        insert T ; 
        
        ContentVersion content=new ContentVersion(); 
        content.Title='Picture1'; 
        content.PathOnClient='/' + content.Title + '.jpg'; 
        Blob bodyBlob=Blob.valueOf(' ContentVersion Body'); 
        content.VersionData=bodyBlob; 
        content.origin = 'H';
        insert content;
		
        ContentDocumentLink contentlink=new ContentDocumentLink();
        contentlink.LinkedEntityId=T.id;
        contentlink.contentdocumentid=[select contentdocumentid from contentversion where id =: content.id].contentdocumentid;
        contentlink.ShareType = 'I';
        contentlink.Visibility = 'AllUsers'; 
        insert contentlink;
        Test.stopTest();
        
    }
}

Hope this helps! Please mark as solved if it does.

Thanks

All Answers

SarvaniSarvani
Hi Carolyn,

In your apex class line 13, SOQL query remove name as there is no such standard field name on Task and it will give error. Try using below test class for 100% coverage.
@isTest public class ContentDocumentLinkTriggerhanlderTest {

  @isTest public static  void testmethod1(){
        Test.startTest();
    
    Id RecordTypeIdTask = [Select Name, Id From RecordType where sObjectType='Task' and isActive=true and name='Task_Record_Type'].id;

        Task T =new Task(Subject='New Test Task',Status='New',Priority='Normal', recordtypeid=RecordTypeIdTask);
        insert T ; 
        
        ContentVersion content=new ContentVersion(); 
        content.Title='Picture1'; 
        content.PathOnClient='/' + content.Title + '.jpg'; 
        Blob bodyBlob=Blob.valueOf(' ContentVersion Body'); 
        content.VersionData=bodyBlob; 
        content.origin = 'H';
        insert content;
		
        ContentDocumentLink contentlink=new ContentDocumentLink();
        contentlink.LinkedEntityId=T.id;
        contentlink.contentdocumentid=[select contentdocumentid from contentversion where id =: content.id].contentdocumentid;
        contentlink.ShareType = 'I';
        contentlink.Visibility = 'AllUsers'; 
        insert contentlink;
        Test.stopTest();
        
    }
}

Hope this helps! Please mark as solved if it does.

Thanks
This was selected as the best answer
Carolyn julianaCarolyn juliana
Thanks sarvani,i have removed name from the code and after test run i got below stack errror
System.QueryException: List has no rows for assignment to SObject

Class.ContentDocLinkTriggerhanlderTest.testmethod1: line 6, column 1
SarvaniSarvani
Hi Carolyn,

The line 6 in the test class is similar to line 6 in your apex classto fetch the record id of "task record type". The error is because it couldn't find and record type on task object with that developername. If your org has record type with developer name Task_Record_Type on task it should not give you this error. However try replacing line 6 in test class with below line as its working in your apex class
Id recordTypeIdTask = Schema.SObjectType.Task.getRecordTypeInfosByName().get('Task_Record_Type').getRecordTypeId();
if you still get the error, in your query editor try execting below SOQL query
Select Name, Id From RecordType where sObjectType='Task' and isActive=true and name='Task_Record_Type'
if the above query doesn't result any record then there seem to be issue with  developer name for the Task record type. Further to fix that and to know correct developer name and name of the record type try executing below:
SELECT Id, Name, DeveloperName FROM RecordType WHERE sObjectType = 'Task'

Hope this helps! 

Thanks
Carolyn julianaCarolyn juliana
Thanks Sarvani,

Now my test clas ran fine with below code ,but the problem is Code coverage is still Zero
 
@isTest public class ContentDocLinkTriggerhanlderTest {
    
    @isTest public static  void testmethod1(){
        Test.startTest();
    
    //Id RecordTypeIdTask = [Select Name, Id From RecordType where sObjectType='Task' and isActive=true and name='Task_Record_Type'].id;
      Id recordTypeId = Schema.SObjectType.Task.getRecordTypeInfosByName().get('Task Record Type').getRecordTypeId();

        Task T =new Task(Subject='New Test Task',Status='New',Priority='Normal', recordtypeid=recordTypeId);
        insert T ; 
        
        ContentVersion content=new ContentVersion(); 
        content.Title='Picture1'; 
        content.PathOnClient='/' + content.Title + '.jpg'; 
        Blob bodyBlob=Blob.valueOf(' ContentVersion Body'); 
        content.VersionData=bodyBlob; 
        content.origin = 'H';
        insert content;
		
        ContentDocumentLink contentlink=new ContentDocumentLink();
        contentlink.LinkedEntityId=T.id;
        contentlink.contentdocumentid=[select contentdocumentid from contentversion where id =: content.id].contentdocumentid;
        contentlink.ShareType = 'I';
        contentlink.Visibility = 'AllUsers'; 
        insert contentlink;
        Test.stopTest();
        
    }

}

 
Carolyn julianaCarolyn juliana
sorry i mean it shows code coverage of trigger as 33%
SarvaniSarvani
Can you please post me the coverage screenshot and Recordtype results for  'Task record type' I am pretty sure something is with that line 6 in class or test class has to be changed. One of them isn't fetching results either in class or test class because your record type name should either be "Task Record Type" or "Task_Record_Type" but cant be both.

Try replacing line 6 in your apex class with below and post the screenshots please.
Id recordTypeId = Schema.SObjectType.Task.getRecordTypeInfosByName().get('Task Record Type').getRecordTypeId();

Thanks
Carolyn julianaCarolyn juliana
Thank you for your continued patience Sarvani on this,finally code worked with your support ,highly appreciated ,actually problem was in my trigger and trigger handler ,here is updated code for 
Apex Trigger "ContentDocLinkTrigger"
trigger ContentDocLinkTrigger on ContentDocumentLink (before insert) {
    if(trigger.isBefore) {
        if(trigger.isInsert) {
            ContentDocumentLinkTriggerHandler.onAfterInsert(trigger.new);
        }
    }

}

Apex Class "ContentDocumentLinkTriggerHandler"
public class ContentDocumentLinkTriggerHandler {
public static void onAfterInsert(list<ContentDocumentLink> lstCntLinks) {
set<Id> setTaskIds = new set<Id>();
list<task> lstTask=new list<task>();
// Id recordTypeId = Schema.SObjectType.Task.getRecordTypeInfosByName().get('Task_Record_Type').getRecordTypeId();
 Id recordTypeId = Schema.SObjectType.Task.getRecordTypeInfosByName().get('Task Record Type').getRecordTypeId();
 
for(ContentDocumentLink clIterator : lstCntLinks) {  
     setTaskIds.add(clIterator.LinkedEntityId);//Set all task id            
 }
 
if(!setTaskIds.isEmpty()) {
                lstTask= [SELECT Id,Attachment_Indicator__c  FROM task WHERE Id IN :setTaskIds and recordtypeid=: recordTypeId ]; //Get all the task 
            }
 
for(task varTsk:  lstTask){
varTsk.Attachment_Indicator__c=true;//Set Attachment Indicator Flag true
 
}
if(lstTask.size()>0){
update lstTask; //update task
         }
    }

    

}



Apex test class "ContentDocLinkTriggerhanlderTest"
@isTest public class ContentDocLinkTriggerhanlderTest {
    
    @isTest public static  void testmethod1(){
        Test.startTest();
    
    //Id RecordTypeIdTask = [Select Name, Id From RecordType where sObjectType='Task' and isActive=true and name='Task_Record_Type'].id;
      Id recordTypeId = Schema.SObjectType.Task.getRecordTypeInfosByName().get('Task Record Type').getRecordTypeId();

        Task T =new Task(Subject='New Test Task',Status='New',Priority='Normal', recordtypeid=recordTypeId);
        insert T ; 
        
        ContentVersion content=new ContentVersion(); 
        content.Title='Picture1'; 
        content.PathOnClient='/' + content.Title + '.jpg'; 
        Blob bodyBlob=Blob.valueOf(' ContentVersion Body'); 
        content.VersionData=bodyBlob; 
        content.origin = 'H';
        insert content;
		
        ContentDocumentLink contentlink=new ContentDocumentLink();
        contentlink.LinkedEntityId=T.id;
        contentlink.contentdocumentid=[select contentdocumentid from contentversion where id =: content.id].contentdocumentid;
        contentlink.ShareType = 'I';
        contentlink.Visibility = 'AllUsers'; 
        insert contentlink;
        Test.stopTest();
        
    }

}



Thank you so much Sravani

Carolyn
 
SarvaniSarvani
Great that you are able to resolve your issue!  Can you please close the thread by marking best answer.

Thanks,
Sarvani
Carolyn julianaCarolyn juliana
Done