Skip to main content
Hello, 

I am trying to create a test class for a recently created trigger, and I am getting an error that Mobile__c is "Invalid field Name for SObject Task". 

The thing is that I have this field (Mobile__c) as an activity custom field and reference it in my trigger without issue. 

Here is the trigger: 

Trigger TaskBefore on Task(before insert, before update){

Map<Id, List<Task>> whoIds = new Map<Id, List<Task>>{};

For (Task t : trigger.new)

If(t.WhoId != null){

List<Task> tasks = whoIds.get(t.WhoId); //this should be t.WhoId (not task.WhoId)

If (tasks == null){

tasks = new List<Task>{};

whoIds.put(t.WhoId, tasks);

}

tasks.add(t);

}

For (Lead ld : [Select Id, Name, MobilePhone from Lead where Id in :whoIDs.keySet()])

For(Task t : whoIds.get(ld.id))

t.Mobile__c = ld.MobilePhone;

For(Contact con : [Select Id, Name, MobilePhone from Contact where Id in :whoIds.keySet()])

For(Task t : whoIds.get(con.id))

t.Mobile__c = con.MobilePhone;

}

And here is my tet class:

 

@isTest

private class TaskBeforeTestClass {

static testMethod void validateTaskBefore() {

Task t = new Task (Name='Validation Test Task', Mobile__c = '');

System.debug('Mobile before insterting new task: ' + t.Mobile__c);

// Insert task

insert t;

//Retrieve the new task

t = [ SELECT Mobile__c FROM Task WHERE Id =:b.Id];

System.debug('Mobile after trigger fired: ' + t.Mobile__c);

// Test that the trigger correctly updated the mobile phone

System.assertNotEquals('', t.Mobile__c);

}

}

My approach here is that I am trying to validate that Mobile__c is BLANK before the trigger fires and not blank after. 

I am pretty new to apex coding, so I really appreciate the help!

Thanks, 

John

 
2 answers
  1. Mar 22, 2016, 12:41 PM
    Hi John,

    Name field does not exist with Task object, so you will have to remove it from the test class while creating Task record. Use subject field instead.

     

    @isTest

    private class TaskBeforeTestClass {

    static testMethod void validateTaskBefore() {

    Task t = new Task (Subject='Validation Test Task', Mobile__c = '');

    System.debug('Mobile before insterting new task: ' + t.Mobile__c);

    // Insert task

    insert t;

    //Retrieve the new task

    t = [ SELECT Mobile__c FROM Task WHERE Id =:b.Id];

    System.debug('Mobile after trigger fired: ' + t.Mobile__c);

    // Test that the trigger correctly updated the mobile phone

    System.assertNotEquals('', t.Mobile__c);

    }

    }

     
0/9000