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
karthik c 53karthik c 53 

hi iam new to salesforce can u provide Test class for trigger

ApexClass
public class OpportunityTriggerClass{
  public static void opportunityCount(List<SObject> newRecords, List<SObject> oldRecords) {
    Map<Id,Account> AccountMap=new Map<Id,Account>();
            set<String> updateOpportunityCount= new Set<String>();
            set<String> accId=new Set<String>();
            for(SObject newObj :newRecords) {
                Opportunity newOppObj = (Opportunity)newObj;//type casting
                Opportunity oldOppObj = null;
                if(newOppObj.Id!=null && oldRecords!=null) {
                    newOppObj = (Opportunity)newObj;//type casting
                }
                if(newOppObj.AccountId!=null){
                accId.add(newOppObj.AccountId);
                }
            }

                for(Account ac:[Select Id,Opportunity_Count__c,(select Id from Opportunities) from Account where Id IN:accId]){
                    ac.Opportunity_Count__c=ac.Opportunities.size(); 
                    AccountMap.put(ac.Id,ac);
                }

            update AccountMap.values();
    }
}



Trigger

trigger OpportunityTrigger on Opportunity (After Insert,After update,After Delete,After Undelete) {
 List<Opportunity> Opportunities = Trigger.isDelete ? Trigger.old : Trigger.new;
    System.debug('Opportunities----'+Opportunities);
    OpportunityTriggerClass.opportunityCount(Opportunities,Opportunities);//calling Apex class method
}
Maulik D ShahMaulik D Shah
Hello Karthik,
 
try this,
 
@isTest
Private class OpportunityTreggerTest {
	@isTest
    public static void OppTestMethod() {
        Account a = new Account();
        a.Name = 'TestAccount';
        Insert a;
        
        Opportunity op = new Opportunity();
        op.Name = 'testopp';
        op.CloseDate = System.today() + 5;
        op.StageName = 'Closed Won';
        op.Amount = 5000;
        op.AccountId = a.Id;
        insert op;
    }
}

I hope this helps you.