+ Start a Discussion
ChiyanChiyan 

how to write a test code

trigger RollUpOppAmt on Opportunity (after insert) {
    
    Set<Id> setOpportunityIds=new Set<Id>();
    for(Opportunity o:Trigger.new)
        setOpportunityIds.add(o.id);
    
    List<Account> ListOfAmt = [select id, Amount__c from Account];
    List<Account> lstAmtToUpdate=new List<Account>();
    
    for(AggregateResult result:[SELECT AccountId, SUM(Amount) FROM Opportunity 
                                WHERE Id IN :setOpportunityIds GROUP BY AccountId]) {
        for(Account acc : ListOfAmt) {
            if(result.get('AccountId') == acc.Id) {
                if(acc.Amount__c == null) {
                    acc.Amount__c = 0;
                }
                acc.Amount__c = acc.Amount__c + Decimal.ValueOf(String.ValueOf(result.get('expr0')));
                lstAmtToUpdate.add(acc);
            }
        }
    }
    if(lstAmtToUpdate.size()>0) {
        UPDATE lstAmtToUpdate;
    }
}
Best Answer chosen by Chiyan
Steven NsubugaSteven Nsubuga
@isTest
private class RollUpOppAmtTest{
        
    @isTest static void testTrigger(){

        Account acc = new Account(name='Test Acc');
        insert acc;
        
        List<Opportunity> opps = new List<Opportunity>();
        for (Integer i = 1; i < 3; i++) {
            Opportunity opp = new Opportunity(AccountId = acc.Id, name = acc.name + i, closedate = system.today(), stagename='Prospecting', Amount = 100 + i);
            opps.add(opp);
        }
        insert opps;
        
        Account acct = [SELECT Amount__c from Account where Id = :acc.Id LIMIT 1];
        System.assertEquals(acct.Amount__c, 203);
    }
}