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
SFDC GuestSFDC Guest 

How to cover the map value in apex test class ?

Hi All,

Please let me know how to cover the Map in test class.

Map<Id,Id> mapIdString = new Map<Id,Id>();

for(sObject sObj: ObjList){
            Id sLastMod = (Id)sObj.get(Label.LastModifiedById);

Piyush G PatelPiyush G Patel
Hi, I have prepared sample code, please do small required changes as per your requirement. Please note this is just sample code and not following best practice, can be referenced for your learning purpose only. These samples covers 100% coverage for map value, which is your request.
public class myFeb18Class1 {
	public static Map<Id,Id> mapIdString = new Map<Id,Id>();
    public static Map<Id,Id> myMethod(List<Account> accountList){
		for(Account a: accountList){
            Id sLastMod = (Id)a.LastModifiedById;
        return mapIdString;
private class myFeb18Class1Test {
    private static void myTestMethod1(){
		Account a1 = new Account(Name='21FebTest1');
        Account a2 = new Account(Name='21FebTest2');
        List<Account> accountLists = new List<Account>();
        insert accountLists;
        Map<Id,Id> mapIdString1 = myFeb18Class1.myMethod(accountLists);
        Integer i = mapIdString1.size();
        for (Account a : accountLists){
            Id myTempId = a.Id;

Suraj Tripathi 47Suraj Tripathi 47

"Try this code."
private class TestClass1{
    static void myTestMethod1(){
        Account ac1 = new Account();
        Account ac2 = new Account();
        List<Account> accList = new List<Account>();
        accList .add(ac1);
        accList .add(ac2);
        insert accList ;
        Map<Id,Id> mapId = TestClass1.method1(accList);
        Integer i = mapId.size();
        for (Account ac : accList {
            Id accId = ac.Id;
            System.assertEquals(ac.LastModifiedById,mapId .get(accId));

If you find your Solution then mark this as the best answer. 

Thank you!

Suraj Tripathi
DigiTarget TechiezDigiTarget Techiez
Maps are an incredibly useful data structure that allows us to store and retrieve data based on a key-value pair. to understand the map and how you can cover the test coverage. Please follow the blog link below which can help you and explain you map and how you can cover it into test classes.

How to Cover Map in Test Class in Salesforce: Best Practices and Tips (

Please review the blog and if you find your solution there,then, please like this comment.