Activity Forums Salesforce® Discussions How can we implement a test class on map in Salesforce apex?

  • shradha jain

    Member
    August 21, 2018 at 9:32 am

    Hello Anurag,

    You can refer the following example to implement a test class of Map:

    Apex Class:

    public class Task14 {

    public static void beforeupdate(Map<id,Account> oldmap,Map<id,Account> newmap){
    list<id> accid=new list<id>();
    for(id key:oldmap.keySet()){
    Account old=oldmap.get(key);
    Account newmp=newmap.get(key);
    if(old.Phone!=newmp.Phone){
    accid.add(key);
    }
    }
    list<Contact> con=[select lastname,firstname,phone,accountid from Contact where accountid in:accid];
    for(Contact c:con){
    Account a=newmap.get(c.accountid);
    Account b=oldmap.get(c.accountid);
    c.Phone=a.Phone;
    c.OtherPhone=b.phone;

    }
    update con;
    }
    }
    Trigger:

    trigger Task14Trigger on Account (before update) {
    if(trigger.isbefore && trigger.isupdate){
    Task14.beforeupdate(Trigger.oldmap, Trigger.newmap);
    }
    }

    Test Class:

    @isTest
    private class Task14_Test {

    @isTest static void beforeupdateTest() {
    Map<id,Account> oldmap = new Map<id,Account>();
    Map<id,Account> newmap = new Map<id,Account>();
    Account acct = new Account(Name='Test Account',phone='123456789');
    insert acct;
    oldmap.put(acct.id, acct);

    contact con = new contact();
    con.accountid = acct.id;
    con.LastName = 'TestContact';
    insert con;

    // Perform test
    Test.startTest();
    acct.Phone = '987654321';
    update acct;
    newmap.put(acct.id, acct);

    Task14.beforeupdate(oldmap,newmap);
    Test.stopTest();

    system.assertEquals('987654321', acct.Phone);
    }

    }

    Thanks.

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos