+ Start a Discussion
Chinna SfdcChinna Sfdc 

Need Test class Help

Hi Team,

Facing the issues on Trigger test class code coverage. as of now code coverage is showing only 20% Let me know the test class written is correct or not Please help me to get 100% code coverage Any help very much appreciated : Below is the Trigger and Test class.

Trigger:

trigger TaskEmailNotification on Task(after update){
 if(TaskEmailNotification.someValue){
    TaskEmailNotification.someValue = false; 
    Set<Id> setopportunityids = new Set<Id>();
    for(Task tsk: Trigger.New){    
        string taskwhatid = tsk.Whatid;
        system.debug('tsk.whatid___'+taskwhatid);        
        if(tsk.Status=='Completed'&&Trigger.oldMap.get(tsk.Id).Status != 'Completed' && tsk.OwnerId != tsk.CreatedById && tsk.Whatid != null && taskwhatid.startsWith('009') && !setopportunityids.contains(tsk.WhatId)){
            setopportunityids.add(tsk.whatid);
        }   
    }
   
    Map<Id,opportunity> MapofidandOpportunity = new Map<Id,opportunity>([select Name,id,ownerid from opportunity where Id in :setopportunityids ]);
    Map<Id,user> Mapofoppidanduser = new Map<Id,user>();
    if(MapofidandOpportunity != null && MapofidandOpportunity.size() > 0){
       set<id> ownerids = new set<id>();
        for(opportunity objopp : MapofidandOpportunity.values()){
            ownerids.add(objopp.ownerid);
        }
        if(ownerids != null && ownerids.size() > 0){
           
            Map<Id,User> Mapofidanduser = new Map<Id,User>([select id, name, email, managerid, manager.email, UserRole.Name from user where id in:ownerids AND UserRole.Name LIKE 'Test%' ]); 
            if(Mapofidanduser != null && Mapofidanduser.size() > 0){
                for(opportunity objopp : MapofidandOpportunity.values()){
                    if(Mapofidanduser.get(objopp.ownerid) != null)
                    Mapofoppidanduser.put(objopp.id,Mapofidanduser.get(objopp.ownerid));
                }
            }
        }
    }
    if(Mapofoppidanduser != null && Mapofoppidanduser.size() > 0){
        List<Messaging.SingleEmailMessage> emailMsglist=new List<Messaging.SingleEmailMessage>();
        for(Task tsk : Trigger.New){
            //system.debug('tsk.whatid___'+tsk.what.type);
            if(tsk.Status == 'Completed' && Trigger.oldMap.get(tsk.Id).Status != 'Completed' &&  tsk.whatid != null &&    Mapofoppidanduser.get(tsk.whatid) != null){                
                User theUser = Mapofoppidanduser.get(tsk.whatid);               
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                list<String> toAddresses = new list<String>(); 
                toAddresses.add(theUser.email);
                //if(theUser.Managerid != null)
                if(theUser.Managerid != null && tsk.Subject.startsWith('Help'))   
                toAddresses.add(theUser.Manager.email);
                mail.setToAddresses(toAddresses);    // Set the TO addresses 
                mail.setSubject('A Task has been updated');   // Set the subject 
                //Next, create a string template. Specify {0}, {1} etc. in place of actual values.
                String template = 'Hello {0}, \n\nYour Task has been Completed. Here are the details - \n\n';
                //template+='Subject: '+tsk.Subject+' \n\n';
                template+= 'Subject: '+'"'+tsk.Subject+'"'+' \n';
                template+='Status: '+tsk.Status +' \n';
                template+='Priority: '+tsk.Priority +' \n';
                template+='DueDate: '+tsk.ActivityDate+'\n';
                template+='Comments: '+tsk.Description +'\n';
                template+='Related To: '+tsk.WhatID+' \n'; 
                template+='\n\nFor more details, click the following link: \n';
                template+=URL.getSalesforceBaseUrl().toExternalForm() + '/' + tsk.Id;
                List<String> args = new List<String>();     
                args.add(theUser.Name);
                // Here's the String.format()
                String formattedHtml = String.format(template, args);
                mail.setPlainTextBody(formattedHtml);
                emailMsglist.add(mail);
            }
        }
        if(emailMsglist != null && emailMsglist.size() > 0)
        system.debug('emailMsglist'+emailMsglist.size());
        Messaging.SendEmail(emailMsglist);
    }
  }
}

Test Class :

@isTest(seeAllData=true)
public class TaskEmailNotificationTest{    
    static testMethod void doEmailNotificationTest(){        
        //Test.startTest();
        Account acc = new Account();            
        acc.Name='TestAcc';                    
        acc.salesAreaList__c = '';            
        acc.BillingCountry = 'SLOVAKIA';            
        acc.BillingCity = 'test city';            
        acc.BillingStreet = 'test street';            
        acc.ShippingCountry = 'SLOVAKIA';                     
        insert acc; 
        
        Profile ps = [SELECT Id FROM Profile WHERE Name='Test']; 
        list<User> lstuser = [SELECT Id,Name FROM User where UserRole.name LIKE 'Test%'];

        Opportunity Opp1 = Test.getOpportunity();
        Opp1.AccountId = acc.Id;
        Opp1.ownerid = lstuser[0].id;        
        insert Opp1;
        
       Test.startTest();  
        Task t = new task();
        //task.Owner = 'test';
        t.Subject = 'Message Sent';
        t.ActivityDate=system.Today();
        t.status = 'In progress';
        t.Priority = 'Low'; 
        t.OwnerId = lstuser[0].id;
        t.WhatId=Opp1.id;
        //task.WhoId=Opp.id;
        insert t;
        t.status = 'Completed';
        update t;        
        System.assertEquals (t.Status,'Completed');

    Test.stopTest();        
    }
}

Thanks
Best Answer chosen by Chinna Sfdc
Amit Chaudhary 8Amit Chaudhary 8
Please try below code
@isTest(seeAllData=true)
public class TaskEmailNotificationTest
{    
    static testMethod void doEmailNotificationTest()
	{
	
        Account acc = new Account();            
        acc.Name='TestAcc';                    
        acc.salesAreaList__c = '';            
        acc.BillingCountry = 'SLOVAKIA';            
        acc.BillingCity = 'test city';            
        acc.BillingStreet = 'test street';            
        acc.ShippingCountry = 'SLOVAKIA';                     
        insert acc; 
        
        list<User> lstuser = [SELECT Id,Name FROM User where UserRole.name LIKE 'Test%'];

        Opportunity Opp1 = Test.getOpportunity();
			Opp1.AccountId = acc.Id;
			Opp1.ownerid = lstuser[0].id;       
			Opp1.Name = 'sha';
			Opp1.StageName = 'Prospecting';
			Opp1.closedate = System.today() + 30;	
        insert Opp1;
        
       Test.startTest();  
TaskEmailNotification.someValue = true;
        Task t = new task();
			t.Subject = 'Message Sent';
			t.ActivityDate=system.Today();
			t.status = 'In progress';
			t.Priority = 'Low'; 
			t.OwnerId = lstuser[0].id;
			t.WhatId=Opp1.id;
        insert t;
		
        TaskEmailNotification.someValue = true; 
        t.status = 'Completed';
        update t;        
        System.assertEquals (t.Status,'Completed');

    Test.stopTest();        
    }
}

Let us know if this will help you
 

All Answers

Amit Chaudhary 8Amit Chaudhary 8
Try to add all required field in test class
@isTest(seeAllData=true)
public class TaskEmailNotificationTest
{    
    static testMethod void doEmailNotificationTest()
	{
	
        Account acc = new Account();            
        acc.Name='TestAcc';                    
        acc.salesAreaList__c = '';            
        acc.BillingCountry = 'SLOVAKIA';            
        acc.BillingCity = 'test city';            
        acc.BillingStreet = 'test street';            
        acc.ShippingCountry = 'SLOVAKIA';                     
        insert acc; 
        
        list<User> lstuser = [SELECT Id,Name FROM User where UserRole.name LIKE 'Test%'];

        Opportunity Opp1 = Test.getOpportunity();
			Opp1.AccountId = acc.Id;
			Opp1.ownerid = lstuser[0].id;       
			Opp1.Name = 'sha';
			Opp1.StageName = 'Prospecting';
			Opp1.closedate = System.today() + 30;	
        insert Opp1;
        
       Test.startTest();  
        Task t = new task();
			t.Subject = 'Message Sent';
			t.ActivityDate=system.Today();
			t.status = 'In progress';
			t.Priority = 'Low'; 
			t.OwnerId = lstuser[0].id;
			t.WhatId=Opp1.id;
        insert t;
		
        t.status = 'Completed';
        update t;        
        System.assertEquals (t.Status,'Completed');

    Test.stopTest();        
    }
}
Please try to execute above test class and let us know if you will get any error
 
Chinna SfdcChinna Sfdc
Hi Amit,

Thanks for your updates..Still it is showing 21% code coverage. The below lines are not covered .Can you please help me on this.

<set<id> ownerids = new set<id>();
        for(opportunity objopp : MapofidandOpportunity.values()){
            ownerids.add(objopp.ownerid);
        }
        if(ownerids != null && ownerids.size() > 0){
           
            Map<Id,User> Mapofidanduser = new Map<Id,User>([select id, name, email, managerid, manager.email, UserRole.Name from user where id in:ownerids AND UserRole.Name LIKE 'Test%' ]); 
            if(Mapofidanduser != null && Mapofidanduser.size() > 0){
                for(opportunity objopp : MapofidandOpportunity.values()){
                    if(Mapofidanduser.get(objopp.ownerid) != null)
                    Mapofoppidanduser.put(objopp.id,Mapofidanduser.get(objopp.ownerid));
                }
            }
        }
    }
    if(Mapofoppidanduser != null && Mapofoppidanduser.size() > 0){
        List<Messaging.SingleEmailMessage> emailMsglist=new List<Messaging.SingleEmailMessage>();
        for(Task tsk : Trigger.New){
            //system.debug('tsk.whatid___'+tsk.what.type);
            if(tsk.Status == 'Completed' && Trigger.oldMap.get(tsk.Id).Status != 'Completed' &&  tsk.whatid != null &&    Mapofoppidanduser.get(tsk.whatid) != null){                
                User theUser = Mapofoppidanduser.get(tsk.whatid);               
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                list<String> toAddresses = new list<String>(); 
                toAddresses.add(theUser.email);
                //if(theUser.Managerid != null)
                if(theUser.Managerid != null && tsk.Subject.startsWith('Help'))   
                toAddresses.add(theUser.Manager.email);
                mail.setToAddresses(toAddresses);    // Set the TO addresses 
                mail.setSubject('A Task has been updated');   // Set the subject 
                //Next, create a string template. Specify {0}, {1} etc. in place of actual values.
                String template = 'Hello {0}, \n\nYour Task has been Completed. Here are the details - \n\n';
                //template+='Subject: '+tsk.Subject+' \n\n';
                template+= 'Subject: '+'"'+tsk.Subject+'"'+' \n';
                template+='Status: '+tsk.Status +' \n';
                template+='Priority: '+tsk.Priority +' \n';
                template+='DueDate: '+tsk.ActivityDate+'\n';
                template+='Comments: '+tsk.Description +'\n';
                template+='Related To: '+tsk.WhatID+' \n'; 
                template+='\n\nFor more details, click the following link: \n';
                template+=URL.getSalesforceBaseUrl().toExternalForm() + '/' + tsk.Id;
                List<String> args = new List<String>();     
                args.add(theUser.Name);
                // Here's the String.format()
                String formattedHtml = String.format(template, args);
                mail.setPlainTextBody(formattedHtml);
                emailMsglist.add(mail);
            }
        }
        if(emailMsglist != null && emailMsglist.size() > 0)
        system.debug('emailMsglist'+emailMsglist.size());
        Messaging.SendEmail(emailMsglist);
    }
  }
}>

Thanks
Amit Chaudhary 8Amit Chaudhary 8
Please try below code
@isTest(seeAllData=true)
public class TaskEmailNotificationTest
{    
    static testMethod void doEmailNotificationTest()
	{
	
        Account acc = new Account();            
        acc.Name='TestAcc';                    
        acc.salesAreaList__c = '';            
        acc.BillingCountry = 'SLOVAKIA';            
        acc.BillingCity = 'test city';            
        acc.BillingStreet = 'test street';            
        acc.ShippingCountry = 'SLOVAKIA';                     
        insert acc; 
        
        list<User> lstuser = [SELECT Id,Name FROM User where UserRole.name LIKE 'Test%'];

        Opportunity Opp1 = Test.getOpportunity();
			Opp1.AccountId = acc.Id;
			Opp1.ownerid = lstuser[0].id;       
			Opp1.Name = 'sha';
			Opp1.StageName = 'Prospecting';
			Opp1.closedate = System.today() + 30;	
        insert Opp1;
        
       Test.startTest();  
TaskEmailNotification.someValue = true;
        Task t = new task();
			t.Subject = 'Message Sent';
			t.ActivityDate=system.Today();
			t.status = 'In progress';
			t.Priority = 'Low'; 
			t.OwnerId = lstuser[0].id;
			t.WhatId=Opp1.id;
        insert t;
		
        TaskEmailNotification.someValue = true; 
        t.status = 'Completed';
        update t;        
        System.assertEquals (t.Status,'Completed');

    Test.stopTest();        
    }
}

Let us know if this will help you
 
This was selected as the best answer
Chinna SfdcChinna Sfdc
Hi Amith,

Now i got 97% code coverage.I did not covered this line " toAddresses.add(theUser.Manager.email);" Can you please help me to get 100% code coverage for this.

Thanks
Amit Chaudhary 8Amit Chaudhary 8
I hope 97% is good to go.

You can try below code
@isTest(seeAllData=true)
public class TaskEmailNotificationTest
{    
    static testMethod void doEmailNotificationTest()
	{
	
        Account acc = new Account();            
        acc.Name='TestAcc';                    
        acc.salesAreaList__c = '';            
        acc.BillingCountry = 'SLOVAKIA';            
        acc.BillingCity = 'test city';            
        acc.BillingStreet = 'test street';            
        acc.ShippingCountry = 'SLOVAKIA';                     
        insert acc; 
        
        list<User> lstuser = [SELECT Id,Name FROM User where UserRole.name LIKE 'Test%' and Managerid != null ];

        Opportunity Opp1 = Test.getOpportunity();
			Opp1.AccountId = acc.Id;
			Opp1.ownerid = lstuser[0].id;       
			Opp1.Name = 'sha';
			Opp1.StageName = 'Prospecting';
			Opp1.closedate = System.today() + 30;	
        insert Opp1;
        
       Test.startTest();  
        Task t = new task();
			t.Subject = 'Message Sent';
			t.ActivityDate=system.Today();
			t.status = 'In progress';
			t.Priority = 'Low'; 
			t.OwnerId = lstuser[0].id;
			t.WhatId=Opp1.id;
        insert t;
		
        t.status = 'Completed';
        update t;        
        System.assertEquals (t.Status,'Completed');

    Test.stopTest();        
    }
}

Let us know if this will help you

 
Chinna SfdcChinna Sfdc
Hi Amit,

Thanks for entire help on this..Still am not getting 100%code coverage but no probelm..

Thanks