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
Patrick ConnerPatrick Conner 

Test Class on Task Trigger

Hey! I'm not a developer by training but I've attempted to create a trigger and test class to deploy a solution that grabs the last date of a task with the subject "Email:" and places in a custom field "Last Email Date". I'm having issues getting test class coverage. Any insight or points in the the right direction would be hugely helpful! Thanks!

trigger updateContact on Task(After Insert, after Update)

    List<Id> conIds = new List<Id>();
    List<Id> OwnerIds = new List<Id>();
    List<Contact> newConlist =  new List<Contact>();
    String str='Email:';

    List<Contact> conList = [select Last_Email_Date__c from Contact where id in:conIds];

    Map<Id, Contact> conMap = new Map<Id, Contact>([SELECT Id, Last_Email_Date__c FROM Contact WHERE Id IN :conIds]);
    for(Task tsk :
            Contact con = conMap.get(tsk.WhoId);
            con.Last_Email_Date__c = tsk.LastModifiedDate;


    update newConlist;

Test Class:
private class TestupdateContact {
  static testMethod void testupdateContact() {
    Contact c = new Contact(LastName='Test');
    insert c;
    Task tsk = new Task(
    insert tsk;

    c.Last_Email_Date__c=DateTime.parse('05/22/2012 11:46 AM');
    update c;
    String checkString = '05/22/2012 11:46 AM';
    system.assertEquals(checkString, [SELECT Last_Email_Date__c FROM Contact WHERE Id = :c.Id].Description);

Two observations:
  1. Line 14, why are you updating the last_email_date, isn't the trigger supposed to do that automatically when you are inserting a task in Line 12 ?
  2. I don't think you would be able to get the exact time when this was inserted. Datetime fields store seconds as well, and there could be a little difference in the time when you insert the record and when you run assertequals, maybe you can remove your manual update in line 15, and only check if the last_email_date is filled ? or check its date component only ? 
Patrick ConnerPatrick Conner
Thanks so much for your reply! I'll see what I can figure out based on your suggestions.