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
FlexyFlexy 

Writing a test class for apex trigger

Hi Everyone, 
I have this Apex Trigger in Sandbox that check if there is an attachment when Grant is Awarded, I need a test class to Deploy it in the production environment,any help..

trigger AttachmentValidation on Opportunity (before update) {
    
    Set<Id> OpptyIdSet = new Set<Id>();
    
    for(Opportunity oppty : Trigger.new){
        //Validation of the fields
        if(oppty.StageName == 'Grant Awarded'){
              OpptyIdSet.add(oppty.id);          
        }
    }
    
    for(Opportunity oppty : [SELECT id,name,(SELECT Id, LinkedEntityId, ContentDocumentId FROM ContentDocumentLinks) FROM Opportunity WHERE id in:OpptyIdSet]){
        
        if(oppty.ContentDocumentLinks.isEmpty()){
            Trigger.newMap.get(oppty.Id).addError('A Grant Agreement attachment is required. If New Opportunity Stage is Grant Awarded/Completed/Certain, to attach, change the stage to anything other than Grant Awarded/Completed/Renewal - Certain and then save it. Afterwards, edit the opp and change the stage as desired and add the attachment.');
        }
    }
}


Thank you.
 
sachinarorasfsachinarorasf
Hi Flexy,
Here is the test class for your code.
@isTest
private class TestClass{
    @testSetup static void setup(){
	//inserting Opportunity
	Opportunity opportunity = new Opportunity();
	opportunity.Name = 'Tesing';
	opportunity.CloseDate =  date.newInstance(2021, 10, 2);
	opportunity.StageName = 'Qualification';
	opportunity.Amount = 2000;
	insert opportunity;
	}
    @istest
    public static void method(){
	  Opportunity opp = [select Id, StageName from Opportunity Limit 1 ];
	  opp.StageName = 'Grant Awarded';
	  update opp;
    }
}
I hope you find the above solution helpful. If it does, please mark it as the Best Answer to help others too.
Thanks and Regards,
Sachin Arora
www.sachinsf.com
 
FlexyFlexy
Hi Sachinarorasf
Thank you for trying to help.
I tried to run the above code but it was failing. I am trying to figure out what could be the problem.
Do you have any idea of what could be causing the error?