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
dcgb2332dcgb2332 

How to get code coverage on apex trigger

Here's the code, not sure why it's not working when I've deployed it before... 

trigger UpdateAccountName on Task (before update)

    Map<Id, Task> idAccountTaskMap = new Map<Id, Task>();
    for (Task t : Trigger.new) {

        if(t.AccountId != null)
            idAccountTaskMap.put(t.AccountId, t);
    }

    if(idAccountTaskMap.isEmpty()) return;

    Map<Id, Account> accountMap = new Map<Id, Account>([SELECT Name FROM Account WHERE Id = :idAccountTaskMap.keyset()]);

    for(Task a : idAccountTaskMap.values())
    {  
        a.Account_Name__c = accountMap.get(a.AccountId).Name;
    }
}
Ajay K DubediAjay K Dubedi
Hi,

I have written the test class with 100% code coverage. 

<<<<----Apex Trigger---->>>>
 
trigger UpdateAccountName on Task (before update)
{ 
    Map<Id, Task> idAccountTaskMap = new Map<Id, Task>();
    for (Task t : Trigger.new) {

        if(t.AccountId != null)
            idAccountTaskMap.put(t.AccountId, t);
    }

    if(idAccountTaskMap.isEmpty()) return;

    Map<Id, Account> accountMap = new Map<Id, Account>([SELECT Name FROM Account WHERE Id = :idAccountTaskMap.keyset()]);

    for(Task a : idAccountTaskMap.values())
    {  
        a.Account_Name__c = accountMap.get(a.AccountId).Name;
    }
}


<<<<----Test Class---->>>>
 
@isTest
private class CreateTask {
    
    @isTest static void createTask1(){
        
        Account accObject = new Account();
        accObject.Name = 'TASK';
        Insert accObject;
        
        Task taskobject = new Task();
        taskobject.WhatID = accObject.id;
        taskobject.Subject = 'subject';
        Insert taskobject;
        System.debug('taskobject-->>'+taskobject);
        taskobject.Subject = 'subject1';
        Update taskobject;
    }
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Ajay Dubedi
www.ajaydubedi.com