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 Beginnersfdc Beginner 

Test Class for Owner Change Trigger

I have a trigger for Which I need to Write a Test Class.

Trigger:
 
trigger AccountShareWhenOwnerChage on Account (after update) {

        Set<Id> OwnerChangedAccs = new Set<Id>();
        
        for(Account a : trigger.new){
            if(trigger.oldMap.ContainsKey(a.id)  && a.ownerid != trigger.oldMap.get(a.id).ownerid){
              OwnerChangedAccs.add(a.id);
           }
        }
    
        List<AccountShare> lstAccShare = new List<AccountShare>(); 
    
        for(Account_Share__c aShare : [SELECT Id, Account__c, User__c FROM Account_Share__c WHERE Account__c IN :OwnerChangedAccs]){
            AccountShare as = new AccountShare();
            as.UserOrGroupID = aShare.User__c;
            as.AccountId = aShare.Account__c;
            as.AccountAccessLevel = 'Edit';
            lstAccShare.add(as);
        }
        insert lstAccShare;
    }
    
}





Test Class:
@isTest
public class TestAccountOwnerChange{

    public static testMethod void unitTest(){
    
        Account a = new Account();
        a.name = 'Test Account';
        insert a;
        
         
        User u = new User();
        u.FirstName = 'Test';
        u.LastName  = 'User';
        u.Email     = 'testuser@gmail.com';
        u.Username  = 'testuser@gmail.com';
        u.Alias     = 'testy';
        u.ProfileId = '00ei0000001NKcq';
        u.TimeZoneSidKey    = 'America/Denver';
        u.LocaleSidKey      = 'en_US';
        u.EmailEncodingKey  = 'UTF-8';
        u.LanguageLocaleKey = 'en_US';
       
        insert u;
        
        Account ua = [SELECT Id,Name,Owenrid FROM Account WHERE Id = :a.id];
        ua.ownerid = u.id;
        update ua;
        
        
        Account_Share__c as = new Account_Share__c();
        as.Account__c = a.id;
        as.User__c = u.id;
        insert as;
        

        

        List<AccountShare> ashares = [SELECT Id, UserOrGroupId, AccountaccessLevel,

        RowCause FROM AccountShare WHERE AccountId = :as.Account__c AND UserOrGroupId= :u.Id];
        
        
        
        
        
        
        
        
    }

}


I have Written a Test Class for this  but it gives me only 60% code Coverage, Can you please help me in Increasing My Code Coverage
suggesting some changes.



Thanks,
SFDC Beginner



 
JeffreyStevensJeffreyStevens
What lines are not getting covered?  (Use DevConsole to find out).

Hard coding the profile ID on line could be problematic - if you don't have a full-sandbox also.
AdamDawAdamDaw
I second the comment on hardcoding the profile ID. It would be better to retrieve a profile via SOQL and use that.