+ Start a Discussion
Carlos LabastidaCarlos Labastida 

Error on test case for Case trigger

Hello. Starting on Apex and runnign into some testing trouble.. I wrote a trigger for updating the Last Update time for a Case when a related Task is created: 
trigger updateCaseByTask on Task (before insert) {
    list<id> caseIds = new list<id>();   
    
// Find if this task is related to a Case
    for(Task t : Trigger.new){
       if(string.valueOf(t.whatId).startsWith('500')){
          caseIds.add(t.whatId);
       }
    }
    
// Update Case to refresh Last Update 
    if (caseIds.size() > 0) {
      List<Case> caseList = [SELECT Id FROM Case WHERE Id IN :caseIds];
      update caseList;
    }
}

The trigger is working great. I then wrote a test for it, using an existing Test case I created specificaly for this:
 
@isTest
public class updateCaseByTaskTest {

    @isTest static void testTaskCreation(){
        Case testCase = [SELECT Id, Subject, Status FROM Case WHERE Subject = 'Case to test updateCaseByTask trigger - DO NOT DELETE' Limit 1];
						

        String caseNumber = testCase.CaseNumber;
        DateTime caseLastModified = testCase.LastModifiedDate;
        Task testTask = new Task();
        // Fill out required Task fields
        testTask.WhatId = testCase.Id;
        testTask.Subject = 'Call';
        testTask.Priority = 'Normal';
        testTask.Status = 'In Progress';
        insert testTask;

        System.assertNotEquals(caseLastModified, testTask.LastModifiedDate);      
    }
}

When I run the query in the Developer's Console Query Editor (
SELECT Id, Subject, Status FROM Case WHERE Subject = 'Case to test updateCaseByTask trigger - DO NOT DELETE' Limit 1), it returns the record, but when the test runs it, it is not finding any result, and giving the error:

System.QueryException: List has no rows for assignment to SObject
Class.updateCaseByTaskTest.testTaskCreation: line 4, column 1


Am I missing anything obvious? Is there a certain format I should write the SOQL on?

Thanks for your help!