Activity › Forums › Salesforce® Discussions › How can we implement a test class on map in Salesforce apex?
Tagged: Method in Apex Class, Salesforce Apex Class, Salesforce Apex Code, Test Class, Test Class in Salesforce
-
How can we implement a test class on map in Salesforce apex?
Posted by Anurag algoworks on July 5, 2018 at 1:44 PMHow can we implement a test class on map in Salesforce apex?
shradha jain replied 7 years, 8 months ago 2 Members · 1 Reply -
1 Reply
-
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.