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

Error on Test Class for Task Trigger



I have the following simple trigger to add a custom field called "Account Name" on the task object:


trigger TaskLinkToParentAccount on Task(before insert, before update) {

    for(Task e : {
        String Link_Id = e.WhoId;
        String Account_ID = '';  
        String Account_Name = '';
        if    (
            Link_Id.startsWith('003')//Contact link
            Account_ID = [SELECT AccountId FROM Contact WHERE id = :Link_Id limit 1].AccountId;
            Account_Name = [SELECT Name FROM Account WHERE id = :Account_ID limit 1].Name;

        e.Account_Name__c = Account_Name;


Here is the test class:


public static testMethod void testTaskLinkToParentAccount(){     
    Account a = new Account(name='TestAccount');
    insert a;
    Contact c = new Contact(lastname='Smith');
    insert c;
    Task t = new Task(subject='test',;
    insert t;


I am getting the following error when I try to validate deployment:


*** Deployment Log ***
# Test Results:

Run Failures:
  testClass.testTaskLinkToParentAccount System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, TaskLinkToParentAccount: execution of BeforeInsert

caused by: System.QueryException: List has no rows for assignment to SObject

Trigger.TaskLinkToParentAccount: line 12, column 28: []


This trigger runs fine in the sandbox so I'm missing something in the test class. Hopefully an easy fix. Any ideas?



Best Answer chosen by Admin (Salesforce Developers) 

Your Test Class isn't linking the contact c to the account a. The trigger cannot then get the account from the contact.

Not sure why it would work in your sandbox.