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
Luiz FLuiz F 

Trigger - Test Class

Can someone help me writing a test class for the following trigger:

trigger updateAttach on Attachment (after insert) {
Map<Id, Id> mapCSId = new map<Id, Id>();
    List<Recrutamento__c> lstCSUpdate = new List<Recrutamento__c>();
    String objectName = '';
    for(Attachment atc: trigger.new){
        String myIdPrefix = string.valueOf(atc.ParentId).substring(0,3);
        Map<String, Schema.SObjectType> gd =  Schema.getGlobalDescribe(); 
        for(Schema.SObjectType stype : gd.values()){
            Schema.DescribeSObjectResult r = stype.getDescribe();
            String prefix = r.getKeyPrefix();
            if(prefix!=null && prefix.equals(myIdPrefix)){
                objectName = r.getName();
            }
        }
        if(objectName == 'Recrutamento__c'){
            mapCSId.put(atc.ParentId, atc.id);
        }
    }
    if(!mapCSId.isEmpty()){
        List<Recrutamento__c> updateAtt = [select id from Recrutamento__c where id in: mapCSId.keyset()];
        for(Recrutamento__c cs: updateAtt){
            cs.AttachmentId__c = mapCSId.get(cs.id);
        }
        if(!updateAtt.isEmpty()){
            update updateAtt;
        }
    }
}



Thanks
Best Answer chosen by Luiz F
Maharajan CMaharajan C
Hi Luiz,

Please write the test class like below:
public class updateAttachTest
{
    static testmethod void testAttach()  
    {
		// Add if any remaining mandatory fields are required for Recrutamento__c record creation in below line
        Recrutamento__c obj = new Recrutamento__c(Name ='Test Record');
        insert obj;

        Attachment att=new Attachment();
        att.Body=Blob.valueOf('test');
        att.Name='test';
        att.ParentId=obj.Id;
		test.startTest();
			insert att;
		test.stopTest();
    }
}

Thanks,
Maharajan.C

All Answers

Maharajan CMaharajan C
Hi Luiz,

Please write the test class like below:
public class updateAttachTest
{
    static testmethod void testAttach()  
    {
		// Add if any remaining mandatory fields are required for Recrutamento__c record creation in below line
        Recrutamento__c obj = new Recrutamento__c(Name ='Test Record');
        insert obj;

        Attachment att=new Attachment();
        att.Body=Blob.valueOf('test');
        att.Name='test';
        att.ParentId=obj.Id;
		test.startTest();
			insert att;
		test.stopTest();
    }
}

Thanks,
Maharajan.C
This was selected as the best answer
Luiz FLuiz F
Thank you Maharajan, it worked!